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? If I just for loop the vowel then I could have gotten the answer but I'm asked to use std::find.. 开发者_Go百科Thanks.
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.
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
.
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).
Use:
size_t find_first_of ( char c, size_t pos = 0 ) const;
Reference: 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. 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
精彩评论