> How do I split a string in C++?

How do I split a string in C++?

Posted at: 2014-12-18 
A delimiter is always going to delimit your string. You don't get to say do your job here, here, but not here. What you *can* do is put the two strings back together (with a comma in the middle if you need it) by concatenating the 3 strings (example: new_string = "b" + ", " + "c").

#include

using namespace std;

int main()

{

int j = 0, n = 0, flag = 0;

string input_line;



getline(cin, input_line);



for(int i = 0; i < input_line.length(); i++)

{



if(input_line.at(i) == '"')

{

if(flag == 0)

flag = 1;

else

flag = 0;

}



if(input_line.at(i) == ',' && flag == 0)

{

if(input_line.at(n) == '"')

{

n++;

j = j - 2;

}



cout << input_line.substr(n,j) << endl;

j = 0;

n = i + 1;

}

else

j++;

}

cout << input_line.substr(n,j) << endl;



return 0;

}

I have a string in C++ that I want to break into multiple strings. I want to use a comma (,) as the delimiter. So, for example, "a,b,c" would be broken into three strings: "a", "b", and "c". I know how to do this much.

The problem is that I don't always want to split the string at every instance of that delimiter. For example, if I had the string "a,"b,c",d" (one string), I would want to split it into three strings: "a", "b,c", and "d". In essence, since the string 'contains' a string ("b,c") I want to keep it as that single sequence.

How can I do this?