C ++按行分割字符串 [英] C++ split string by line

查看:337
本文介绍了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[] = "\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方法。但是当我调试时,我发现句子参数是我们是一个人。是的,我们是,并且拆分失败。有人可以告诉我为什么会这样,我该怎么办。无论如何,还有其他我可以用来在C ++中拆分字符串的方法。谢谢!

I input "we are one.\nyes 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,'\n')){
      cout << to <<endl;
    }
  }

return 0;
}

这篇关于C ++按行分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆