Please tell a newbie how to split a string into multiple substrings using the delimiter character entered from the console? So far, I manage to get a string of only the first and last match by the separator, but I need to split the entire text.
Code:
cout & lt; & lt; "Enter text here:" & lt; & lt; flush;
string text;
getline (cin, text);
string delim;
cout & lt; & lt; "Enter symbol:" & lt; & lt; flush;
cin & gt; & gt; delim;
string :: size_type pos = text.find (delim);
string :: size_type posl = text.rfind (delim);
string first = text.substr (0, pos);
string second = text.substr (pos + delim.length ());
string last = text.substr (posl + delim.length ());
const char * cfirst = first.c_str ();
const char * csecond = second.c_str ();
const char * clast = last.c_str ();
cout & lt; & lt; cfirst & lt; & lt; endl;
cout & lt; & lt; csecond & lt; & lt; endl;
cout & lt; & lt; clast & lt; & lt; endl;
Answer 1, authority 100%
The task is called split. And for some reason, it was not explicitly added to stl. But there is a wagon of solutions – https: //www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/ or https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words -of-a-string
I liked this solution –
char sep = '';
std :: string s = "1 This is an example";
for (size_t p = 0, q = 0; p! = s.npos; p = q)
std :: cout & lt; & lt; s.substr (p + (p! = 0), (q = s.find (sep, p + 1)) - p- (p! = 0)) & lt; & lt; std :: endl;
Answer 2
A simple way to get a vector of strings using std :: stringstream
static std :: vector & lt; std :: string & gt; split (const std :: string & amp; s, char delim)
{
std :: vector & lt; std :: string & gt; elems;
std :: stringstream ss (s);
std :: string item;
while (std :: getline (ss, item, delim)) {
elems.push_back (item);
}
return elems;
}