检查字符串是否包含大写或小写字母
Check if string has letter in uppercase or lowercase
我想知道是否可以检查字符串中的一个字母是否大写。另一种查看方式,如果字符串中的所有字母都是大写或小写。示例:
string a = "aaaaAaa";
string b = "AAAAAa";
if(??){ //Cheking if all the string is lowercase
cout << "The string a contain a uppercase letter" << endl;
}
if(??){ //Checking if all the string is uppercase
cout << "The string b contain a lowercase letter" << endl;
}
这可以使用 lambda 表达式轻松完成:
if (std::count_if(a.begin(), b.end(), [](unsigned char ch) { return std::islower(ch); }) == 1) {
// The string has exactly one lowercase character
...
}
这假设您想要根据您的示例准确检测一个 uppercase/lowercase 字母。
你可以使用标准算法std::all_of
if( std::all_of( str.begin(), str.end(), islower ) ) { // all lowercase
}
与isupper
和islower
一起使用all_of
:
if(all_of(a.begin(), a.end(), &::isupper)){ //Cheking if all the string is lowercase
cout << "The string a contain a uppercase letter" << endl;
}
if(all_of(a.begin(), a.end(), &::islower)){ //Checking if all the string is uppercase
cout << "The string b contain a lowercase letter" << endl;
}
或者,如果您想检查与您的谓词匹配的字母数,请使用 count_if
。
我想知道是否可以检查字符串中的一个字母是否大写。另一种查看方式,如果字符串中的所有字母都是大写或小写。示例:
string a = "aaaaAaa";
string b = "AAAAAa";
if(??){ //Cheking if all the string is lowercase
cout << "The string a contain a uppercase letter" << endl;
}
if(??){ //Checking if all the string is uppercase
cout << "The string b contain a lowercase letter" << endl;
}
这可以使用 lambda 表达式轻松完成:
if (std::count_if(a.begin(), b.end(), [](unsigned char ch) { return std::islower(ch); }) == 1) {
// The string has exactly one lowercase character
...
}
这假设您想要根据您的示例准确检测一个 uppercase/lowercase 字母。
你可以使用标准算法std::all_of
if( std::all_of( str.begin(), str.end(), islower ) ) { // all lowercase
}
与isupper
和islower
一起使用all_of
:
if(all_of(a.begin(), a.end(), &::isupper)){ //Cheking if all the string is lowercase
cout << "The string a contain a uppercase letter" << endl;
}
if(all_of(a.begin(), a.end(), &::islower)){ //Checking if all the string is uppercase
cout << "The string b contain a lowercase letter" << endl;
}
或者,如果您想检查与您的谓词匹配的字母数,请使用 count_if
。