Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ split string by double newline

Tags:

c++

string

split

I have been trying to split a string by double newlines ("\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);

gives me the output

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

which is obviously not what I wanted. I need to get something like

[first line
second line]
[third line
fourthline]

I have also tried boost::split but it gives me the same result. What am I missing?

like image 287
none Avatar asked Jul 07 '12 08:07

none


2 Answers

find_first_of only looks for single characters. What you're telling it to do by passing it "\n\n", is to find the first of either '\n' or '\n', and that's redundant. Use string::find instead.

boost::split also works by examining only one character at a time.

like image 119
Benjamin Lindley Avatar answered Nov 16 '22 07:11

Benjamin Lindley


How about this approach:

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

It gives me:

[firstline
secondline]
[thirdline
fourthline]

as the result, which is basically what you wanted, right?

like image 1
Roland Avatar answered Nov 16 '22 09:11

Roland