有没有一种方法可以检查这些情况?或者我是否需要解析字符串中的每个字母,并检查它是否是小写字母(字母)并且是数字/字母?
它并不是很有名,但是语言环境实际上确实具有一次确定整个字符串特征的功能。具体来说,一个语言环境的ctype
方面有一个scan_is
和一个scan_not
,它扫描适合指定掩码的第一个字符(字母,数字,字母数字,下部,上部,标点符号,空格,十六进制数字等),或者第一个字符。分别不适合它。除此之外,它们的工作方式有点像std::find_if
,返回任何你传递的“结束”信号失败,否则返回指向字符串中第一个不符合你要求的项目的指针。
这是一个快速示例:
#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
- 使用它几乎相同,但可以很容易地推广到更多的情况。即使它的适用性要窄得多,但用户并不是那么容易(虽然我想如果你要扫描大块文本,它可能至少要快一点)。
假设“C”语言环境是可接受的(或交换为criteria
的不同字符集),请使用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);
}
您可以使用tolower&strcmp来比较original_string和tolowered string。并且每个字符单独执行数字。
(或)每个角色如下所示。
#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();
}
我使用了以下信息:Determine if a string contains only alphanumeric characters (or a space)
如果您的字符串包含ASCII编码的文本,并且您想编写自己的函数(就像我一样),那么您可以使用:
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::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'); }