C++如何通过两个换行符分割字符串

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,但结果是一样的。我错过了什么吗?
3个回答

5
find_first_of 只查找单个字符。通过传递 "\n\n",你要求它查找第一个 '\n''\n',这是多余的。请改用string::find

boost::split 也仅检查一个字符。


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]

因此,这基本上就是您想要的结果,对吧?


-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

这并不是OP所要求的,你将“input”按每个单独的“\n”分割,即使它在这种情况下产生了“正确”的(打印)结果,你也应该按两个“\n”分割它。 - Filip Roséen - refp
@refp:它确实可以完成OP所要求的功能,但是方式不同。 - Nawaz
1
我一直在尝试通过双换行符拆分字符串,但你没有使用双换行符进行拆分。 - Filip Roséen - refp
1
@refp: 他是对的,只是他输出的方式不太清晰。这是他代码的一个微小修改,可以更清楚地表达:http://ideone.com/n3c5Q - Benjamin Lindley
@refp: 此外,您一再强调我的解决方案没有进行“双行”拆分。我认为这是短视的,因为我的解决方案甚至没有进行单行拆分。它以我在答案中所说的不同方式完成工作。 - Nawaz
显示剩余10条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接