我想在字符串(word)中找到一个char(expected_char)
if (word.find(expected_char)==true)
{
cout << "You got one! It's on pos" << word.find(expected_char);
}
else
{
...
}
如果我的字符串是例如“abcd”并且我搜索“c”,否则将执行;如果我搜索“b”,则将执行 if 语句。
我想在字符串(word)中找到一个char(expected_char)
if (word.find(expected_char)==true)
{
cout << "You got one! It's on pos" << word.find(expected_char);
}
else
{
...
}
如果我的字符串是例如“abcd”并且我搜索“c”,否则将执行;如果我搜索“b”,则将执行 if 语句。
的返回类型std::string::find()是无符号类型std::string::size_type,如果未找到字符,则返回std::string::npos(可以表示的最大值std::string::size_type)或字符串中找到的字符的第一个索引。
现在您将 的结果与 的结果进行比较std::string::find(),true这会导致布尔值整体提升为true整数值1。因此,当且仅当expected_char在位置 1 中找到字符时(即,当它是字符串中的第二个字符时),您的条件才满足。
如果要检查字符expected_char是否在字符串word中,请使用
if (word.find(expected_char) != std::string::npos)
{
...
}
看到这个你就明白了。有趣的部分:
std::string str("There are two needles in this haystack with needles.");
std::string str2("needle");
unsigned found = str.find(str2);
if (found != std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
find返回一个位置,npos如果没有匹配则返回特殊值。你需要测试:
word.find(expected_char) != word.npos
(恰好b在位置 1,这也是 的整数值true。)