有没有办法比较单个字符和一组字符?
例如:
char a;
if(a in {'q','w','e','r','t','y','u'})
return true;
else return false;
Run Code Online (Sandbox Code Playgroud)
我需要这样的东西.
Eri*_*rik 15
std::string chars = "qwertyu";
char c = 'w';
if (chars.find(c) != std::string::npos) {
// It's there
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用一组 - 如果您需要经常查找更快.
std::set<char> chars;
char const * CharList = "qwertyu";
chars.insert(CharList, CharList + strlen(CharList));
if (chars.find('q') != chars.end()) {
// It's there
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如史蒂夫杰西普的建议:你也可以用chars.count('q')而不是find('q') != end()
您也可以使用当前字符的位图(例如vector<bool>),但这过于复杂,除非您每秒执行几百万次.
Mar*_*tos 11
使用strchr:
return strchr("qwertyu", a);
Run Code Online (Sandbox Code Playgroud)
没有必要写,"if x return true else return false,"just,"return x".