Найти уникальный идентификатор и доменное имя веб-сайта из строки

Опубликовано: 22 Сентября, 2022

Для заданной строки S размера N , состоящей из уникального идентификатора и доменного имени уникального веб-сайта, задача состоит в том, чтобы найти идентификатор и доменное имя в заданной строке, если идентификатор имеет вид [char, char, char, char, символ, цифра, цифра, цифра, цифра, символ] .

Примеры:

Input: S = “We thank ABCDE1234F for visiting us and buying products item AMZrr@!k. For more offers, visit us at www.amazon.com”
Output:
ID = ABCDE1234F
Domain = amazon.com

Input: S = “Hi PQRST5678D, it was a pleasure to host you. See www.oyo.com, our official website for future stays”
Output:
ID = PQRST5678D
Domain = oyo.com

Подход: Самый простой подход к решению данной проблемы — разбить строку на слова и определить, является ли разделенная строка идентификатором или доменом . Выполните следующие шаги, чтобы решить проблему:

  • Сначала разделите слова строки, разделенные пробелом, и сохраните их в векторе строки saywords [] .
  • Инициализируйте две пустые строки, скажем, ID и Domain , чтобы сохранить результирующие ID и Domain Name .
  • Пройдите по вектору строки words[] и выполните следующие шаги:
    • Инициализируйте переменную, скажем, пометьте как false , чтобы сохранить, соответствует ли текущая строка формату идентификатора или нет.
    • Если длина текущей строки равна 10 и если первые 5 символов и последний символ не являются буквами или любой из оставшихся символов строки не является числовым, то пометьте флаг как true .
    • Если значение флага равно false , то присвойте текущую строку идентификатору .
    • Если первая подстрока текущей строки, скажем, SS в диапазоне [0, 2] — это « www », а подстрока в диапазоне [SS.length() — 3, SS.length() — 1] — « com », тогда назначьте доменное имя, т. е. подстроку в диапазоне [3, SS.length() – 1] для Domain .
  • После выполнения вышеуказанных шагов выведите в качестве результата значение ID и домена .

Ниже приведена реализация вышеуказанного подхода:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a character is
// alphabet or not
bool ischar(char x)
{
    if ((x >= "A" && x <= "Z")
        || (x >= "a" && x <= "z")) {
        return 1;
    }
 
    return 0;
}
 
// Function to check if a character is
// a numeric or not
bool isnum(char x)
{
    if (x >= "0" && x <= "9")
        return 1;
    return 0;
}
 
// Function to find ID and Domain
// name from a given string
void findIdandDomain(string S, int N)
{
    // Stores ID and the domain names
    string ID, Domain;
 
    // Stores the words of string S
    vector<string> words;
 
    // Stores the temporary word
    string curr = "";
 
    // Traverse the string S
    for (int i = 0; i < N; i++) {
 
        // If the current character
        // is space
        if (S[i] == " ") {
 
            // Push the curr in words
            words.push_back(curr);
 
            // Update the curr
            curr = "";
        }
 
        // Otherwise
        else {
            if (S[i] == ".") {
 
                if (i + 1 == N
                    || (i + 1 < N
                        && S[i + 1] == " "))
                    continue;
            }
            curr += S[i];
        }
    }
 
    // If curr is not empty
    if (curr.length())
        words.push_back(curr);
 
    for (string ss : words) {
 
        // If length of ss is 10
        if (ss.size() == 10) {
            bool flag = 0;
 
            // Traverse the string ss
            for (int j = 0; j <= 9; j++) {
 
                // If j is in the range
                // [5, 9)
                if (j >= 5 && j < 9) {
 
                    // If current character
                    // is not numeric
                    if (isnum(ss[j]) == 0)
 
                        // Mark flag 1
                        flag = 1;
                }
 
                // Otherwise
                else {
 
                    // If current character
                    // is not alphabet
                    if (ischar(ss[j]) == 0)
 
                        // Mark flag 1
                        flag = 1;
                }
            }
 
            // If flag is false
            if (!flag) {
 
                // Assign ss to ID
                ID = ss;
            }
        }
 
        // If substring formed by the
        // first 3 character is "www"
        // and last 3 character is "moc"
        if (ss.substr(0, 3) == "www"
            && ss.substr(
                   ss.length() - 3, 3)
                   == "com") {
 
            // Update the domain name
            Domain = ss.substr(
                4, ss.size() - 4);
        }
    }
 
    // Print ID and Domain
    cout << "ID = " << ID
         << endl;
    cout << "Domain = " << Domain;
}
 
// Driver Code
int main()
{
    string S = "We thank ABCDE1234F for visiting "
               "us and buying "
               "products item AMZrr@!k. For more "
               "offers, visit "
               "us at www.amazon.com";
    int N = S.length();
    findIdandDomain(S, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if a character is
// alphabet or not
static boolean ischar(char x)
{
    if ((x >= "A" && x <= "Z") ||
        (x >= "a" && x <= "z"))
    {
        return true;
    }
    return false;
}
 
// Function to check if a character is
// a numeric or not
static boolean isnum(char x)
{
    if (x >= "0" && x <= "9")
        return true;
         
    return false;
}
 
// Function to find ID and Domain
// name from a given String
static void findIdandDomain(String S, int N)
{
     
    // Stores ID and the domain names
    String ID = "", Domain = "";
 
    // Stores the words of String S
    Vector<String> words = new Vector<String>();
 
    // Stores the temporary word
    String curr = "";
 
    // Traverse the String S
    for(int i = 0; i < N; i++)
    {
         
        // If the current character
        // is space
        if (S.charAt(i) == " ")
        {
             
            // Push the curr in words
            words.add(curr);
 
            // Update the curr
            curr = "";
        }
 
        // Otherwise
        else
        {
            if (S.charAt(i) == ".")
            {
                 
                if (i + 1 == N || (i + 1 < N &&
                    S.charAt(i + 1) == " "))
                    continue;
            }
            curr += S.charAt(i);
        }
    }
 
    // If curr is not empty
    if (curr.length() > 0)
        words.add(curr);
 
    for(String ss : words)
    {
         
        // If length of ss is 10
        if (ss.length() == 10)
        {
            boolean flag = false;
 
            // Traverse the String ss
            for(int j = 0; j <= 9; j++)
            {
 
                // If j is in the range
                // [5, 9)
                if (j >= 5 && j < 9)
                {
 
                    // If current character
                    // is not numeric
                    if (isnum(ss.charAt(j)) == false)
 
                        // Mark flag 1
                        flag = true;
                }
 
                // Otherwise
                else
                {
                     
                    // If current character
                    // is not alphabet
                    if (ischar(ss.charAt(j)) == false)
 
                        // Mark flag 1
                        flag = true;
                }
            }
 
            // If flag is false
            if (!flag)
            {
                 
                // Assign ss to ID
                ID = ss;
            }
        }
 
        // If subString formed by the
        // first 3 character is "www"
        // and last 3 character is "moc"
        if (ss.length() > 2 && ss.substring(0, 3).equals("www") &&
            ss.substring(ss.length() - 3).equals("com"))
        {
 
            // Update the domain name
            Domain = ss.substring(4, ss.length());
        }
    }
 
    // Print ID and Domain
    System.out.print("ID = " +  ID + " ");
    System.out.print("Domain = " +  Domain);
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "We thank ABCDE1234F for visiting " +
               "us and buying products item AMZrr@!k. " +
               "For more offers, visit us at www.amazon.com";
    int N = S.length();
     
    findIdandDomain(S, N);
}
}
 
// This code is contributed by 29AjayKumar

Python3




# Python3 program for the above approach
 
# Function to check if a character is
# alphabet or not
def ischar(x):
     
    if ((x >= "A" and x <= "Z") or
        (x >= "a" and x <= "z")):
        return 1
         
    return 0
 
# Function to check if a character is
# a numeric or not
def isnum(x):
     
    if (x >= "0" and x <= "9"):
        return 1
         
    return 0
 
# Function to find ID and Domain
# name from a given
def findIdandDomain(S, N):
     
    # Stores ID and the domain names
    ID, Domain = "", ""
 
    # Stores the words of  S
    words = []
 
    # Stores the temporary word
    curr = ""
 
    # Traverse the  S
    for i in range(N):
         
       &

РЕКОМЕНДУЕМЫЕ СТАТЬИ