[英]cpp string find() doesnt work as expected - returns big junk values
I'm trying to find the index of a substring in another string, using find(), but getting a junk value and not std::npos if the substring is not there. 我正在尝试使用find()在另一个字符串中查找子字符串的索引,但是如果该子字符串不存在,则会得到一个垃圾值,而不是std :: npos。
This is the Code: 这是代码:
string output1 = "abcd";
字符串output1 =“ abcd”;
cout << output.find("gf") << endl;
cout << output.find(“ gf”)<< endl;
And this is the output: 这是输出:
18446744073709551615
18446744073709551615
can this behaviour be prevented? 可以防止这种行为吗? is there another way to find the substring?
还有另一种查找子字符串的方法吗?
(actually i only need to find if the substring is contained) (实际上,我只需要查找是否包含子字符串)
Thank you 谢谢
What it return is size_t
of npos of your string because it can't find your char or text. 它返回的是字符串npos的
size_t
,因为它找不到您的字符或文本。 you can do this instead: 您可以改为:
std::size_t found = str.find("findme");
if (found != std::string::npos)
std:cout << found << std::endl;
else
std::cout << "String not found" << std::endl // If not found
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.