C 逐行分割字符串

新手上路,请多包涵

我需要逐行拆分字符串。我以前是按以下方式做的:

 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;
}

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

原文由 wangzhiju 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 780
2 个回答

我想使用 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;
}

原文由 billz 发布,翻译遵循 CC BY-SA 3.0 许可协议

#include <sstream>
#include <string>
#include <vector>

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;
}

原文由 Oleksandr Kozlov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题