HTML Entity Parser

Опубликовано: 9 Января, 2022

Учитывая строку str, содержащую различные объекты HTML, задача состоит в том, чтобы заменить эти объекты соответствующими специальными символами.

HTML entity parser is the parser that takes HTML code as input and replaces all the entities of the special characters by the characters itself. The special characters and their entities for HTML are Quotation Mark: the entity is ", and symbol character is “.

Ниже представлены объекты HTML с соответствующими специальными символами, приведенными в таблице ниже:

Имя / Описание HTML-объект Особый персонаж
Космос & nbsp;
Амперсанд & amp; &
Больше чем & gt; >
Меньше, чем & lt; <
Одинарная кавычка & апос; '
Двойные кавычки & quot; "
Торговая марка & reg; Знак авторского права & копировать; Косая черта & frasl;

Примеры:

Input: str = “17 &gt; 25 and 25 &lt; 17”
Output: 17 > 25 and 25 < 17
Explanation: In the above example &gt; is
replaced by corresponding special character
> and &lt; is replaced by <

Input: str = “&copy; is symbol of copyright”
Output: © is symbol of copyright
Explanation: In the above example &copy; is
replaced by corresponding special character
©

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Метод 1 - использование unordered_map: Ниже приведены шаги:

  1. Сохраните HTML-объект с его персонажем на карте.
  2. Пройдите по заданной строке и, если встретится какой-либо символ '&' , найдите, какой HTML-объект присутствует после этого амперсанда.
  3. Добавьте соответствующий символ с Entity в строку вывода.
  4. В качестве результата выведите строку вывода.

Below is the implementation of the above approach:

C++

// C++ program for the above approach
#include <iostream>
#include <unordered_map>
using namespace std;
  
class GfG {
public:
    unordered_map<string, string> m;
  
public:
    // Associating html entity with
    // special character
    void initializeMap()
    {
        m["""] = """;
        m["""] = """;
        m["&"] = "&";
        m[">"] = ">";
        m["<"] = "<";
        m["⁄"] = "/";
        m[" "] = " ";
        m["®"] = "";
        m["©"] = "";
    }
  
public:
    // Function that convert the given
    // HTML Entity to its parsed String
    string parseInputString(string input)
    {
        // Output string
        string output = "";
  
        // Traverse the string
        for (int i = 0;
             i < input.size(); i++) {
  
            // If any ampersand is occurred
            if (input[i] == "&") {
  
                string buffer;
  
                while (i < input.size()) {
  
                    buffer = buffer + input[i];
  
                    // If any Entity is found
                    if (input[i] == ";"
                        && m.find(buffer)
                               != m.end()) {
  
                        // Append the parsed
                        // character
                        output = output
                                 + m[buffer];
  
                        // Clear the buffer
                        buffer = "";
                        i++;
                        break;
                    }
                    else {
                        i++;
                    }
                }
  
                if (i >= input.size()) {
                    output = output
                             + buffer;
                    break;
                }
                i--;
            }
            else {
                output = output
                         + input[i];
            }
        }
  
        // Return the parsed string
        return output;
    }
};
  
// Driver Code
int main()
{
    // Given String
    string input = "17 > 25 and 25 < 17";
    GfG g;
  
    // Initialised parsed string
    g.initializeMap();
  
    // Function Call
    cout << g.parseInputString(input);
    return 0;
}
Output:
17 > 25 and 25 < 17

Сложность времени: O (N)
Вспомогательное пространство: O (N)

Метод 2 - использование сопоставления с шаблоном:
Ниже приведены шаги:

  1. Пройдите по заданной строке str .
  2. Если во время обхода встречается какой-либо символ '&' , найдите, какой HTML-объект присутствует после этого амперсанда.
  3. Добавьте соответствующий символ с Entity в строку вывода из приведенной выше таблицы совпадающих символов в приведенной выше таблице.
  4. Распечатайте выходную строку как результат после обхода указанной выше строки.

Below is the implementation of the above approach:

C++

// C++ program to Parse the HTML Entities
#include <iostream>
using namespace std;
  
class GfG {
  
public:
    string parseInputString(string input)
    {
  
        // To store parsed string
        string output = "";
  
        for (int i = 0;
             i < input.size(); i++) {
  
            // Matching pattern of html
            // entity
            if (input[i] == "&") {
                string buffer;
  
                while (i < input.size()) {
                    buffer = buffer + input[i];
  
                    // Check match for ()
                    if (input[i] == ";"
                        && buffer == """) {
                        output = output + """;
                        buffer = "";
                        i++;
                        break;
                    }
  
                    // Check match for (")
                    else if (input[i] == ";"
                             && buffer == """) {
                        output = output + """;
                        buffer = "";
                        i++;
                        break;
                    }
  
                    // Check match for (&)
                    else if (input[i] == ";"
                             && buffer == "&") {
                        output = output + "&";
                        buffer = "";
                        i++;
                        break;
                    }
  
                    // Check match for (>)
                    else if (input[i] == ";"
                             && buffer == ">") {
                        output = output + ">";
                        buffer = "";
                        i++;
                        break;
                    }
  
                    // Check match for (<)
                    else if (input[i] == ";"
                             && buffer == "<") {
                        output = output + "<";
                        buffer = "";
                        i++;
                        break;
                    }
  
                    // Check match for (/)
                    else if (input[i] == ";"
                             && buffer == "⁄") {
                        output = output + "/";
                        buffer = "";
                        i++;
                        break;
                    }
  
                    // Check match for (" ")
                    else if (input[i] == ";"
                             && buffer == " ") {
                        output = output + " ";
                        buffer = "";
                        i++;
                        break;
                    }
  
                    // Check match for ()
                    else if (input[i] == ";"
                             && buffer == "®") {
                        output = output + "";
                        buffer = "";
                        i++;
                        break;
                    }
  
                    // Check match for ()
                    else if (input[i] == ";"
                             && buffer == "©") {
                        output = output + "";
                        buffer = "";
                        i++;
                        break;
                    }
                    else {
                        i++;
                    }
                }
  
                if (i >= input.size()) {
                    output = output + buffer;
                    break;
                }
                i--;
            }
            else {
                output = output + input[i];
            }
        }
  
        // Return the parsed string
        return output;
    }
};
  
// Driver Code
int main()
{
    // Given String
    string input = "17 > 25 and 25 < 17";
    GfG g;
  
    // Initialised parsed string
    g.initializeMap();
  
    // Function Call
    cout << g.parseInputString(input);
    return 0;
}
Output:

17 > 25 and 25 < 17