C++ 逐行拆分字符串

C++ split string by line(C++ 逐行拆分字符串)

本文介绍了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;
}

这篇关于C++ 逐行拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 逐行拆分字符串

基础教程推荐