我有以下代码:-
string name = "hello world";
size_t find = name.find("world");
if (find != string::npos) {
cout<<"match found at "<<find;
}
else{
cout<<find;
}
该程序运行良好,并按预期打印 6 个输出。
但是如果我将其更改为 size_t find = name.find('\n');
它将垃圾值打印为 18446744073709551615
。 find函数在没有找到匹配的字符串时会打印垃圾值吗??
最佳答案
引自http://www.cplusplus.com/reference/string/string/find/
Return Value
The position of the first character of the first match. If no matches were found, the function returns string::npos.
size_t is an unsigned integral type (the same as member type string::size_type).
因此,您的函数会打印 std::string::npos,例如在 MSVS std 库实现中是
basic_string<_Elem, _Traits, _Alloc>::npos =
(typename basic_string<_Elem, _Traits, _Alloc>::size_type)(-1);
64 位系统上的最大 unsigned int 值是:18,446,744,073,709,551,615,请参阅 https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
您可以将代码更改为
string name = "hello world";
size_t find = name.find("world");
if (find != string::npos) {
cout<<"match found at "<<find;
}
else {
cout<<"match not found";
}
关于c++ - 当没有字符串匹配时,在 String 中查找函数会输出垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37476994/