Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a c++ string into two parts

Tags:

c++

string

I'm trying to split a string that contains "|" into two parts.

if (size_t found = s.find("|") != string::npos)
{
    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?

like image 889
neuromancer Avatar asked Oct 17 '25 03:10

neuromancer


1 Answers

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)
like image 75
James McNellis Avatar answered Oct 18 '25 16:10

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!