頭文件#include <cctype>
輸出包含的標點符號
#include <iostream> #include <string> #include <cctype> int main() { std::string s1 = "lolita is a beautiful girl ? yes !"; //輸出其中的標點符號 for(auto c : s1) if(ispunct(c)) std::cout<<c<<std::endl; return 0; }
將所有小寫轉換為大寫字母
#include <iostream> #include <string> #include <cctype> int main() { std::string s1 = "lolita is a beautiful girl ? yes !"; for(auto &c : s1) if(islower(c)) c = toupper(c); std::cout<<s1<<std::endl; return 0; }
將首個單詞大寫
#include <iostream> #include <string> #include <cctype> int main() { std::string s1 = "lolita is a beautiful girl ? yes !"; for(decltype(s1.size()) index = 0 ; index<s1.size()&&!isspace(s1[index]); index++) { s1[index] = toupper(s1[index]); } std::cout<<s1<<std::endl; return 0; }
判斷首字母大小寫
#include <iostream> #include <string> #include <cctype> int main() { std::string s1 = "lolita is a beautiful girl ? yes !"; if(s1.size()>0) //很重要 { if(isupper(s1[0])) { std::cout<<"首字母大寫"<<std::endl; } else { std::cout<<"首字母小寫"<<std::endl; } } else { std::cout<<"空字符串"<<std::endl; } return 0; }