[英]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)
{
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.这适用于“a | b”,但对于“a | b”,它将具有“| b”作为右侧。 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
.因此,
found
将始终为1
或0
。 You need to declare found
outside of the condition and use some parentheses:您需要在条件之外声明
found
并使用一些括号:
size_t found;
if ((found = s.find("|")) != string::npos)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.