解题思路:
用英文、数字等对应的ASCii码来解决,不要string一个字符串,直接char一个字符型数组,然后输入字符串,后续针对每一个字符进行判断就很方便。
注意事项:
不#include<cstring>的话过不了编译,会告诉你[Error] 'strlen'was not declared in this scope,不过在本地编译器上是正常编译的。
另外cin和scanf()遇到空格直接当作输入结束了,所以要用cin.get()来接收带空格的字符串。
参考代码:
#include <iostream> #include <cstring> using namespace std; int main() { int letter = 0; int digit = 0; int space = 0; int other = 0; char str[200]; cin.get(str, 200); //cin和scanf遇到空格当作结束 int len = strlen(str); for(int i = 0; i < len; i++) { if((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 && str[i] <= 122)) { letter++; } else if(str[i] >= 48 && str[i] <= 57) { digit++; } else if(str[i] == 32) { space++; } else { other++; } } cout << letter << " " << digit << " " << space << " " << other << endl; return 0; }
0.0分
6 人评分
林惜城 2022-04-12 16:02:40 |
遍历字符型数组str里的每一个元素,看每个字符的ASCii码属于字母还是数字还是什么的,然后对应的个数+1
qss 2022-04-13 00:11:32 |
@reminder 嗷明白了谢谢您