解题思路:
1、定义四个变量分别计数不同类型的字符
2、根据每个字符的类型进行判断
字母:'A' <= str[i] <= 'Z' || 'a' <= str[i] <= 'z'
空格:str[i] == ' '
数字:'0' <= str[i] <='9'
其他:else
参考代码:
#include <iostream> #include <string> using namespace std; int main() { string str; getline(cin,str); int count1 = 0, //字母 count2 = 0, //空格 count3 = 0, //数字 count4 = 0; //其他 for(int i = 0; i < str.length(); ++i) { if((str[i]>='A' && str[i]<='Z') || (str[i]>='a' && str[i]<='z')) count1++; else if(str[i] == ' ') count2++; else if(str[i]>='0' && str[i]<='9') count3++; else count4++; } cout << count1 << endl; cout << count2 << endl; cout << count3 << endl; cout << count4 << endl; return 0; }
0.0分
0 人评分