問題是我想比較一個字符串中的字符,對於每個字符,它是否屬於字母表;是小寫還是大寫。我怎麼能這樣做?將一個字符與C++中的各種字符類進行比較
這是很好,如果我想比較它像(+ - * ^)像沒有標準功能。 PLZ幫我出
問題是我想比較一個字符串中的字符,對於每個字符,它是否屬於字母表;是小寫還是大寫。我怎麼能這樣做?將一個字符與C++中的各種字符類進行比較
這是很好,如果我想比較它像(+ - * ^)像沒有標準功能。 PLZ幫我出
#include <cctype>
#include <string>
...
for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
if (std::isalpha(*i))
handle_alphabetic_character(*i);
else
handle_non_alphabetic_character(*i);
編輯新的要求:
要查找任意字符集,你可以使用任何STR :: find()方法在他的回答詹姆斯MeNellis文件,或者乾脆...
#include <cstring>
for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
if (std::strchr("*+{\\&", *i))
handle_matching_character(*i);
else
handle_non_matching_character(*i);
您可以輕鬆地使用std::find
算法:
const std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
bool is_in_alphabet
= std::find(alphabet.begin(), alphabet.end(), 'c') != alphabet.end();
或者,如果字母字符是排序的,則可以使用std::binary_search
,但除非字母表中的字符數很多(即大於26),否則線性搜索可能會快得多。字符很小,而且很快比較。
感謝託尼ü太偉大和計算器太 – maverick 2011-02-04 06:22:21
PLZ看看我編輯的問題 – maverick 2011-02-04 06:36:45