【问题标题】:What is the best way to tokenize a string in C++? [duplicate]在 C++ 中标记字符串的最佳方法是什么? [复制]
【发布时间】:2014-03-01 22:37:42
【问题描述】:

我尝试使用 strtok(),但它给出了分段错误。谁能告诉我代码中的问题出在哪里,除了 strtok() 之外,还有没有更好的方法来标记字符串?

void tokenize(char *tagToFind, char *record, char *delim)
{
    char *token;
    char *itr;
    char *tag;
    char *tag5;
    int toBreak=0;
    token = strtok(record,delim);
    while (token != NULL)
    {
            itr = token;
            while (*itr != '{')
            {
                    tag = itr;
                    itr++;
                    tag++;
            }
            tag = '\0';
            if ((strcmp(tag, tagToFind) == 0))
                    break;
            else
                    token = strtok(NULL,delim);
    }

    if(strcmp(tag5, "tag5") == 0)
    {
            cout<<"\n\n\n\n\t\ttag5 is present.";
    }
}

int main()
{
    char *tag = "tag5";
    char *record = "tag1{0}|tag2{0}|tag3{0}|tag4{0}|tag5{tag51{0};tag52{0};tag53{0};tag54{0};tag55{tag551{0}:tag552{0}:tag553{0}:tag554{0}:tag555{0}}}";
    char *delim = "|";
    tokenize(tag, record, delim);
    return 0;
}

【问题讨论】:

标签: c++


【解决方案1】:
char const* const tag = "tag5";
char const* const record = "tag1{0}|tag2{0}|tag3{0}|tag4{0}|tag5{tag51{0};tag52{0};tag53{0};tag54{0};tag55{tag551{0}:tag552{0}:tag553{0}:tag554{0}:tag555{0}}}";
char const delim = '|';

std::stringstream ss(record);
for (std::string token; std::getline(ss, token, delim); ) {
    // Handle token here.
}

Example here.

【讨论】:

  • 非常感谢这个例子。
  • @Mariners 如果接受这个答案应该点击右边,并且不要忘记阅读@JohnBode's answer
【解决方案2】:

您遇到了段错误,因为您在 字符串文字 上使用了strtok。请记住,strtok 修改了输入字符串(它将分隔符的所有实例替换为 0),并且修改字符串文字会导致未定义的行为;在某些平台上(显然是你的平台),字符串文字存储在只读内存段中,因此会出现错误。

您的代码应该适用于以下更改:

char record[] = "tag1{0}|tag2{0}|tag3{0}|tag4{0}|tag5{tag51{0};tag52{0};tag53{0};tag54{0};tag55{tag551{0}:tag552{0}:tag553{0}:tag554{0}:tag555{0}}}";

record 不再是指向字符串文字的指针,而是现在可以由您的代码修改的 char 数组。

话虽如此,如果您使用的是 C++,Simple 的解决方案可能是更好的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    相关资源
    最近更新 更多