简单的C ++标记化器

问题描述 投票:-2回答:2

我正在编写一个针对HackerRank挑战的程序,我需要解析HRML,一种类似于HTML的标记语言:

<tag1 value = "Hello World"></tag1>

作为程序的一部分,我有一个函数,它应该用字符串标记填充字符串向量。它适用于标签,但我还需要标记化查询,其格式如下:

tag1.tag2.tag3~attribute_name

该函数的行为类似于字符串迭代器在遇到波形符后停止前进。这是代码:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

void tokenize_string(vector<string>& vector, string str)
{
    string current_token;

    for (auto i = str.begin(); i != str.end(); i++)
    {

        if (isalnum(*i))
        {
            current_token += *i;
        }
        else
        {
            //We extracted a token
            vector.push_back(current_token);
            current_token = "";
        }
    }

    //Remove empty strings that the previous loop placed into the vector
    for (auto i = vector.begin(); i != vector.end(); i++)
    {
         if (*i == "")
        {
            vector.erase(i);
            i = vector.begin();
        }
    }
} 
int main()
{
    //A simple test
    vector<string> tag_tokens;
    vector<string> query_tokens;

    tokenize_string(tag_tokens, "<tag1 name=\"Hello\">");
    tokenize_string(query_tokens, "tag1.tag2.tag3~name");

    for (auto it = tag_tokens.begin(); it != tag_tokens.end(); it++)
    {
        cout << *it << ' ';
    }
    cout << '\n';
    for (auto it = query_tokens.begin(); it != query_tokens.end(); it++)
    {
        cout << *it << ' ';
    }
    cout << '\n';
    cin.get();
    return 0;
}
c++ tokenize
2个回答
0
投票

这是因为在到达输入字符串i != str.end()的末尾之后你没有考虑最后一个标记。 在for循环之后添加vector.push_back(current_token);,如下所示,考虑最后一个标记。

void tokenize_string(vector<string>& vector, string str)
{
    string current_token;

    for (auto i = str.begin(); i != str.end(); i++)
    {

        if (isalnum(*i))
        {
            current_token += *i;
        }
        else
        {
            //We extracted a token
            vector.push_back(current_token);
            current_token = "";
        }
    }
                vector.push_back(current_token);   ///-------->pushes last token

    //Remove empty strings that the previous loop placed into the vector
    for (auto i = vector.begin(); i != vector.end(); i++)
    {
         if (*i == "")
        {
            vector.erase(i);
            i = vector.begin();
        }
    }
}

0
投票

这是一种不同的方法,需要更少的代码行:

void tokenize_string(
    std::vector< std::string >& output,
    const std::string& csv,
    const string& delimiters )
{
    for( char del : delimiters ) {
      std::stringstream sst(csv);
      std::string a;
      while( getline( sst, a, del) )
        output.push_back(a);
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.