Splitting a c++ string into two parts
I'm trying to split a string that contains "|" into two parts.
if (size_t found = s.find("|") != string::npos)开发者_如何学C
{
cout << "left side = " << s.substr(0,found) << endl;
cout << "right side = " << s.substr(found+1, string::npos) << endl;
}
This works with "a|b", but with "a | b", it will have "| b" as the right side. Why is that? How can this be fixed?
size_t found = s.find("|") != string::npos
This is a declaration; it gets parsed as
size_t found = (s.find("|") != string::npos)
So, found
will always be 1
or 0
. You need to declare found
outside of the condition and use some parentheses:
size_t found;
if ((found = s.find("|")) != string::npos)
精彩评论