C++ 逐行拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13172158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:03:17  来源:igfitidea点击:

C++ split string by line

c++split

提问by wangzhiju

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

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 !

我输入“我们是一体的。\不,我们是。” 并调用 doSegment 方法。但是当我调试时,我发现句子参数是“we are one.\\nyes we are”,并且拆分失败。有人可以告诉我为什么会发生这种情况,我应该怎么做。无论如何我可以用来在C++中分割字符串。谢谢 !

回答by billz

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

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

回答by Some programmer dude

You can call std::string::findin a loop and the use std::string::substr.

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

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

See example here.

请参阅此处的示例。

回答by Oleksandr Kozlov

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

回答by Scourge

#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>

using namespace std;


vector<string> splitter(string in_pattern, string& content){
    vector<string> split_content;

    regex pattern(in_pattern);
    copy( sregex_token_iterator(content.begin(), content.end(), pattern, -1),
    sregex_token_iterator(),back_inserter(split_content));  
    return split_content;
}

int main()
{   

    string sentence = "This is the first line\n";
    sentence += "This is the second line\n";
    sentence += "This is the third line\n";

    vector<string> lines = splitter(R"(\n)", sentence);

    for (string line: lines){cout << line << endl;}

}   

//  1) We have a string with multiple lines
//  2) we split those into an array (vector)
//  3) We print out those elements in a for loop


//  My Background. . .  
//  github.com/Radicalware  
//  Radicalware.net  
//  https://www.youtube.com/channel/UCivwmYxoOdDT3GmDnD0CfQA/playlists  

回答by Jelle Bleeker

This fairly inefficient way just loops through the string until it encounters an \n newline escape character. It then creates a substring and adds it to a vector.

这种相当低效的方式只是遍历字符串,直到遇到 \n 换行符。然后它创建一个子字符串并将其添加到一个向量中。

std::vector<std::string> Loader::StringToLines(std::string string)
{
    std::vector<std::string> result;
    std::string temp;
    int markbegin = 0;
    int markend = 0;

    for (int i = 0; i < string.length(); ++i) {     
        if (string[i] == '\n') {
            markend = i;
            result.push_back(string.substr(markbegin, markend - markbegin));
            markbegin = (i + 1);
        }
    }
    return result;
}