C ++如何使用find函数在char数组中查找char?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4060210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ How to find char in a char array by using find function?
提问by Michael Sync
How to find char in a char array by using find function? If I just for loop the vowel then I could have gotten the answer but I'm asked to use std::find.. Thanks.
如何使用find函数在char数组中查找char?如果我只是循环元音,那么我可以得到答案,但我被要求使用 std::find ......谢谢。
bool IsVowel (char c) {
char vowel[] = {'a', 'e', 'i', 'o', 'u'};
bool rtn = std::find(vowel, vowel + 5, c);
std::cout << " Trace : " << c << " " << rtn << endl;
return rtn;
}
回答by Maciej Hehl
bool IsVowel (char c) {
char vowel[] = {'a', 'e', 'i', 'o', 'u'};
char* end = vowel + sizeof(vowel) / sizeof(vowel[0]);
char* position = std::find(vowel, end, c);
return (position != end);
}
回答by eq-
std::find(first, last, value)
returns an iterator to the first element which matches value
in range [first, last). If there's no match, it returns last
.
std::find(first, last, value)
返回一个迭代器,指向value
在 [first, last) 范围内匹配的第一个元素。如果没有匹配项,则返回last
。
In particular, std::find does not return a boolean. To get the boolean you're looking for, you need to compare the return value (without converting it to a boolean first!) of std::find to last
(i.e. if they are equal, no match was found).
特别是, std::find 不返回布尔值。要获得您正在寻找的布尔值,您需要将 std::find 的返回值(而不是先将其转换为布尔值!)与last
(即,如果它们相等,则未找到匹配项)进行比较。
回答by Shreevardhan
Simplifying and correcting
简化和修正
inline bool IsVowel(char c) {
return std::string("aeiou").find(c) != std::string::npos;
}
See a demo http://ideone.com/NnimDH.
回答by iGbanam
Use:
用:
size_t find_first_of ( char c, size_t pos = 0 ) const;
Reference: http://www.cplusplus.com/reference/string/string/find_first_of/
参考:http: //www.cplusplus.com/reference/string/string/find_first_of/