[英]C++ How to find char in a char array by using find function?
How to find char in a char array by using find function?如何使用find函数在char数组中查找char? If I just for loop the vowel then I could have gotten the answer but I'm asked to use std::find.. Thanks.如果我只是循环元音,那么我可以得到答案,但我被要求使用 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;
}
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);
}
Simplifying and correcting简化和修正
inline bool IsVowel(char c) {
return std::string("aeiou").find(c) != std::string::npos;
}
See a demo http://ideone.com/NnimDH .查看演示http://ideone.com/NnimDH 。
std::find(first, last, value)
returns an iterator to the first element which matches value
in range [first, last). std::find(first, last, value)
返回一个迭代器,指向与范围 [first, last) 中的value
匹配的第一个元素。 If there's no match, it returns last
.如果没有匹配项,则返回last
。
In particular, std::find does not return a boolean.特别是, std::find 不返回布尔值。 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
(ie if they are equal, no match was found).要获得您正在寻找的布尔值,您需要将 std::find 的返回值(而不是先将其转换为布尔值!)与last
(即,如果它们相等,则未找到匹配项)。
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/
Looking for the sequence of a character in an array - why drag bool into it.在数组中查找字符的序列 - 为什么将 bool 拖入其中。 Give a simple straightforward answer if you can.如果可以,请给出一个简单明了的答案。
#include <iostream>
#include <stdio.h>
using namespace std;
//Position
int posc(char suit[], char fc, int sz)
{
int i = 0;
do
{
if (toupper(fc) == suit[i]) return i;
else
i = i + 1;
}
while (i < sz);
cout << "\n Character " << fc << " not available in list";
return 99;
}
int main()
{
char suit[] = { 'S', 'D', 'C', 'H' };
char fc;
int res;
int sz = size(suit);
cout << "\n Enter a character: ";
cin >> fc;
res = posc(suit, fc, sz);
cout << "\n Sequence no: " << res;
return 0;
}
The main & cout frills are added just to show a working solution添加主要和 cout 装饰只是为了显示一个有效的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.