C++ 逐行拆分字符串

2021-12-28 00:00:00 split c++

我需要逐行拆分字符串.我以前是这样做的:

I need to split string by line. I used to do in the following way:

int doSegment(char *sentence, int segNum)
{
assert(pSegmenter != NULL);
Logger &log = Logger::getLogger();
char delims[] = "
";
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++ 中拆分字符串.谢谢!

I input "we are one. yes we are." and invoke the doSegment method. But when i debugging, i found the sentence parameter is "we are one.\nyes we are", and the split failed. Can somebody tell me why this happened and what should i do. Is there anyway else i can use to split string in C++. thanks !

推荐答案

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

I'd like to use std::getline or std::string::find to go through the string. below code demonstrates getline function

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

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

return 0;
}

相关文章