Check if string has letter in uppercase or lowercase

梦想的初衷 提交于 2019-12-09 03:36:30

问题


i would like to know if it's possible check if one letter of a string is capitalized. Other way to see it, if all letters in the string are uppercase or lowercase. Example:

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;
}

回答1:


you can use standard algorithm std::all_of

if( std::all_of( str.begin(), str.end(), islower ) { // all lowercase
}



回答2:


Use all_of in concert with isupper and islower:

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;
}

demo

Alternatively, use count_if, if you want to check the number of letters matching your predicate.




回答3:


This can be easily done with lambda expressions:

if (std::count_if(a.begin(), b.end(), [](unsigned char ch) { return std::islower(ch); }) == 1) {
    // The string has exactly one lowercase character
    ...
}

This assumes that you want to detect exactly one uppercase/lowercase letter, as per your examples.



来源:https://stackoverflow.com/questions/40496334/check-if-string-has-letter-in-uppercase-or-lowercase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!