is there a way to compare a single character with a set of characters?
eg:
char a;
if(a in {'q','w','e','r','t','y','u'})
return true;
else return false;
i need something like this.开发者_StackOverflow
std::string chars = "qwertyu";
char c = 'w';
if (chars.find(c) != std::string::npos) {
// It's there
}
Or you could use a set - if you need to lookup often that's faster.
std::set<char> chars;
char const * CharList = "qwertyu";
chars.insert(CharList, CharList + strlen(CharList));
if (chars.find('q') != chars.end()) {
// It's there
}
EDIT: As Steve Jessop's suggested: You can also use chars.count('q')
instead of find('q') != end()
You could also use a bitmap of present chars (e.g. vector<bool>
) but that's overly complex unless you do this a few million times a second.
Use strchr:
return strchr("qwertyu", a);
There's no need to write, "if x return true else return false," just, "return x".
const char[] letters = {...};
char a = ...;
bool found = false;
for(int i = 0; i < sizeof(letters); i++) {
if (letters[i] == a)
found = true;
}
if (found) {
...
} else {
...
}
std::string s="qwertyu";
return s.find(a) != std::string::npos;
精彩评论