[英]C++: string.find finds a char in a string only if its on pos1
我想在字符串(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
。 因此,當且僅當在位置1中找到字符expected_char
(即,它是字符串中的第二個字符)時,您的條件才能滿足。
如果要檢查字符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
的整數值。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.