首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++逐行拆分字符串

C++逐行拆分字符串
EN

Stack Overflow用户
提问于 2012-11-01 14:37:44
回答 5查看 73.7K关注 0票数 38

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

代码语言:javascript
复制
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;
}

我输入“我们是一体的\n是的”并调用doSegment方法。但当我调试时,我发现句子参数是“我们是一体的。\n是的,我们是一体的”,拆分失败。谁能告诉我为什么会这样,我该怎么做。还有没有别的方法可以用来在C++中拆分字符串。谢谢!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-11-01 15:14:33

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

代码语言:javascript
复制
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;
}
票数 71
EN

Stack Overflow用户

发布于 2012-11-01 15:08:17

您可以在循环中调用std::string::find并使用std::string::substr

代码语言:javascript
复制
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;
}

请参阅示例here

票数 17
EN

Stack Overflow用户

发布于 2019-12-10 20:29:57

代码语言:javascript
复制
#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;
}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13172158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档