2011-04-06 113 views

回答

13
std::string chars = "qwertyu"; 
char c = 'w'; 
if (chars.find(c) != std::string::npos) { 
    // It's there 
} 

或者你可以使用一套 - 如果你需要经常查找,速度更快。

std::set<char> chars; 
char const * CharList = "qwertyu"; 
chars.insert(CharList, CharList + strlen(CharList)); 
if (chars.find('q') != chars.end()) { 
    // It's there 
} 

编辑:正如史蒂夫·杰索普的提示:您还可以使用chars.count('q')代替find('q') != end()

您还可以使用当前字符的位图(例如vector<bool>),但除非你做这几百万那是过于复杂每秒一次。

+1

1 C++方法。 – 2011-04-06 10:49:03

+0

@Erik:我建议你至少偷一些我的代码来使用这个集合。 'count'很好:-) – 2011-04-06 10:54:57

+0

@Steve Jessop:没想到'count',从来没有用过嘿嘿。虽然我发现明确的比较结束更可读。 – Erik 2011-04-06 10:59:54

10

和strchr用途:

return strchr("qwertyu", a); 

有没有必要写, “如果x返回TRUE,否则返回false,” 只是, “返回X”。

+0

+1简单,非浪费的方法。 – 2011-04-06 10:49:24

+0

应注意,strchr位于/标题中。 – 2011-04-06 10:50:27

0
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 { 
    ... 
} 
0
std::string s="qwertyu"; 
return s.find(a) != std::string::npos; 
相关问题