有没有一种方法可以检查这些情况?还是说我需要解析字符串中的每个字母,并检查它是否为小写字母(letter)和数字/字母?
有没有一种方法可以检查这些情况?还是说我需要解析字符串中的每个字母,并检查它是否为小写字母(letter)和数字/字母?
find_first_not_of() 。
#include <string>
bool testString(const std::string& str)
{
std::string criteria("abcdefghijklmnopqrstuvwxyz0123456789");
return (std::string::npos == str.find_first_not_of(criteria);
}
std :: find_first_not_of
需要一个内部循环来检查元素是否不在集合中,而不像isdigit
,isalnum
和islower
可以根据语言环境仅使用几个比较。 - phuclv#include <locale>
#include <iostream>
#include <iomanip>
int main() {
std::string inputs[] = {
"alllower",
"1234",
"lower132",
"including a space"
};
// We'll use the "classic" (C) locale, but this works with any
std::locale loc(std::locale::classic());
// A mask specifying the characters to search for:
std::ctype_base::mask m = std::ctype_base::lower | std::ctype_base::digit;
for (int i=0; i<4; i++) {
char const *pos;
char const *b = &*inputs[i].begin();
char const *e = &*inputs[i].end();
std::cout << "Input: " << std::setw(20) << inputs[i] << ":\t";
// finally, call the actual function:
if ((pos=std::use_facet<std::ctype<char> >(loc).scan_not(m, b, e)) == e)
std::cout << "All characters match mask\n";
else
std::cout << "First non-matching character = \"" << *pos << "\"\n";
}
return 0;
}
我猜大多数人会更喜欢使用std :: find_if
,因为使用它几乎相同,但是可以很容易地推广到更多情况。尽管这具有更窄的适用性,但实际上并不比用户更容易(尽管我认为如果您正在扫描大量文本,则可能至少会快一点)。
#include <algorithm>
static inline bool is_not_alphanum_lower(char c)
{
return (!isalnum(c) || !islower(c));
}
bool string_is_valid(const std::string &str)
{
return find_if(str.begin(), str.end(), is_not_alphanum_lower) == str.end();
}
我使用了一些信息来自于: 判断一个字符串是否只包含字母数字字符(或空格)
只需使用{{link1:std::all_of
}}
bool lowerAlnum = std::all_of(str.cbegin(), str.cend(), [](const char c){
return isdigit(c) || islower(c);
});
如果您不关心语言环境(即输入为纯7位ASCII),则可将该条件优化为
[](const char c){ return ('0' <= c && c <= '9') || ('a' <= c && c <= 'z'); }
bool is_lower_alphanumeric(const string& txt)
{
for(char c : txt)
{
if (!((c >= '0' and c <= '9') or (c >= 'a' and c <= 'z'))) return false;
}
return true;
}
std::find
的类似islower
或isalnum
的函数更容易理解。 - Jerry Coffin