用多个定界符将字符串分割成单词

我有一些文本(有意义的文本或算术表达式),我想将其拆分为单词。

如果我只有一个定界符,则可以使用:


std::stringstream stringStream(inputString);

std::string word;

while(std::getline(stringStream, word, delimiter)) 

{

    wordVector.push_back(word);

}

如何使用几个定界符将字符串分成令牌?


料青山看我应如是
浏览 486回答 3
3回答

森栏

假设其中一个定界符是换行符,则以下内容将读取该行,并用定界符进一步对其进行拆分。在此示例中,我选择了定界符空间,撇号和分号。std::stringstream stringStream(inputString);std::string line;while(std::getline(stringStream, line))&nbsp;{&nbsp; &nbsp; std::size_t prev = 0, pos;&nbsp; &nbsp; while ((pos = line.find_first_of(" ';", prev)) != std::string::npos)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (pos > prev)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wordVector.push_back(line.substr(prev, pos-prev));&nbsp; &nbsp; &nbsp; &nbsp; prev = pos+1;&nbsp; &nbsp; }&nbsp; &nbsp; if (prev < line.length())&nbsp; &nbsp; &nbsp; &nbsp; wordVector.push_back(line.substr(prev, std::string::npos));}
打开App,查看更多内容
随时随地看视频慕课网APP