cpp string find() 没有按预期工作 - returns 大垃圾值
cpp string find() doesnt work as expected - returns big junk values
我正在尝试使用 find() 在另一个字符串中查找子字符串的索引,但如果子字符串不存在,则得到的是垃圾值而不是 std::npos。
这是代码:
string output1 = "abcd";
cout << output.find("gf") << endl;
这是输出:
18446744073709551615
可以防止这种行为吗?还有另一种方法可以找到子字符串吗?
(其实我只要找到if子串就可以了)
谢谢
它 return 是 size_t
你的字符串的 npos,因为它找不到你的字符或文本。你可以这样做:
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
我正在尝试使用 find() 在另一个字符串中查找子字符串的索引,但如果子字符串不存在,则得到的是垃圾值而不是 std::npos。
这是代码:
string output1 = "abcd";
cout << output.find("gf") << endl;
这是输出:
18446744073709551615
可以防止这种行为吗?还有另一种方法可以找到子字符串吗?
(其实我只要找到if子串就可以了)
谢谢
它 return 是 size_t
你的字符串的 npos,因为它找不到你的字符或文本。你可以这样做:
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