C++逐行拆分

wan*_*iju 30 c++ split

我需要逐行拆分.我以前用以下方式做的事情:

int doSegment(char *sentence, int segNum)
{
assert(pSegmenter != NULL);
Logger &log = Logger::getLogger();
char delims[] = "\n";
char *line = NULL;
if (sentence != NULL)
{
    line = strtok(sentence, delims);
    while(line != NULL)
    {
        cout << line << endl;
        line = strtok(NULL, delims);
    }
}
else
{
    log.error("....");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我输入"我们是一个.\n \n我们是." 并调用doSegment方法.但是当我调试时,我发现句子参数是"我们是一个.\\nyes we are",并且拆分失败了.有人能告诉我为什么会这样,我该怎么办.有没有其他我可以用来在C++中拆分字符串.谢谢 !

bil*_*llz 52

我想使用std :: getline或std :: string :: find来查看字符串.下面的代码演示了getline函数

int doSegment(char *sentence)
{
  std::stringstream ss(sentence);
  std::string to;

  if (sentence != NULL)
  {
    while(std::getline(ss,to,'\n')){
      cout << to <<endl;
    }
  }

return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 它是局部变量,如果离开doSegment,它将自毁. (6认同)

Som*_*ude 15

你可以调用std::string::find循环和使用std::string::substr.

std::vector<std::string> split_string(const std::string& str,
                                      const std::string& delimiter)
{
    std::vector<std::string> strings;

    std::string::size_type pos = 0;
    std::string::size_type prev = 0;
    while ((pos = str.find(delimiter, prev)) != std::string::npos)
    {
        strings.push_back(str.substr(prev, pos - prev));
        prev = pos + 1;
    }

    // To get the last substring (or only, if delimiter is not found)
    strings.push_back(str.substr(prev));

    return strings;
}
Run Code Online (Sandbox Code Playgroud)

这里的例子.

  • 如果你使用的分隔符有多个字符,就像我一样,你会想要改变"prev = pos + 1;" line to"prev = pos + delimiter.size();" 代替.否则,您将在向量中的下一个元素的开头留下剩余的字符. (9认同)

Ole*_*lov 9

std::vector<std::string> split_string_by_newline(const std::string& str)
{
    auto result = std::vector<std::string>{};
    auto ss = std::stringstream{str};

    for (std::string line; std::getline(ss, line, '\n');)
        result.push_back(line);

    return result;
}
Run Code Online (Sandbox Code Playgroud)