7

我一直在尝试用双换行符 ( "\n\n") 拆分字符串。

input_string = "firstline\nsecondline\n\nthirdline\nfourthline";

size_t current;
size_t next = std::string::npos;
do {
  current = next + 1;
  next = input_string.find_first_of("\n\n", current);
  cout << "[" << input_string.substr(current, next - current) << "]" << endl;
} while (next != std::string::npos);

给我输出

[firstline]
[secondline]
[]
[thirdline]
[fourthline]

这显然不是我想要的。我需要得到类似的东西

[first line
second line]
[third line
fourthline]

我也尝试过boost::split,但它给了我相同的结果。我错过了什么?

4

3 回答 3

5

find_first_of只查找单个字符。您通过传递它来告诉它要做的"\n\n"是找到'\n'or'\n'中的第一个,这是多余的。改为使用string::find

boost::split也可以一次只检查一个字符。

于 2012-07-07T08:29:19.800 回答
1

这种方法怎么样:

  string input_string = "firstline\nsecondline\n\nthirdline\nfourthline";

  size_t current = 0;
  size_t next = std::string::npos;
  do
  {
    next = input_string.find("\n\n", current);
    cout << "[" << input_string.substr(current, next - current) << "]" << endl;
    current = next + 2;
  } while (next != std::string::npos);

它给了我:

[firstline
secondline]
[thirdline
fourthline]

结果,这基本上就是你想要的,对吧?

于 2012-08-08T12:05:14.143 回答
-2

@Benjamin 在他的回答中很好地解释了您的代码不起作用的原因。因此,我将向您展示另一种解决方案。

无需手动拆分。对于您的具体情况,std::stringstream是合适的:

#include <iostream>
#include <sstream>

int main() {
        std::string input = "firstline\nsecondline\n\nthirdline\nfourthline";
        std::stringstream ss(input);
        std::string line;
        while(std::getline(ss, line))
        {
           if( line != "")
                 std::cout << line << std::endl;
        }
        return 0;
}

输出(演示):

firstline
secondline
thirdline
fourthline
于 2012-07-07T08:32:18.783 回答