2012-07-07 93 views
7

我一直试图通过双换行符("\n\n")拆分字符串。C++通过双换行符拆分字符串

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但它给了我同样的结果。我错过了什么?

回答

5

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

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

+0

inc在8分钟内接受答案。非常感谢你 – none 2012-07-07 08:32:36

0

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

输出(demo):

firstline 
secondline 
thirdline 
fourthline 
+0

这不会做OP所要求的,即使你在这种情况下产生了“正确的”(打印的)结果,你也应该将每个'\ n'分开'input' '\ n'。 – 2012-07-07 08:37:55

+0

@refp:它确实做OP的要求,但不同。 – Nawaz 2012-07-07 08:39:00

+1

“我一直试图用双换行符来分割一个字符串”,无处可分。 – 2012-07-07 08:40:19

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] 

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