用C++中的字符串类作为形参统计从键盘输入的字符串中字母、数字、空格和其他字符数的个数
时间: 2023-11-19 19:04:47 浏览: 73
```c
#include <stdio.h>
#include <string.h>
void countChar(char str[]) {
int len = strlen(str);
int letterCount = 0, digitCount = 0, spaceCount = 0, otherCount = 0;
for(int i = 0; i < len; i++) {
char c = str[i];
if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
letterCount++;
} else if(c >= '0' && c <= '9') {
digitCount++;
} else if(c == ' ' || c == '\t' || c == '\n') {
spaceCount++;
} else {
otherCount++;
}
}
printf("Letter count: %d\n", letterCount);
printf("Digit count: %d\n", digitCount);
printf("Space count: %d\n", spaceCount);
printf("Other count: %d\n", otherCount);
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin);
countChar(str);
return 0;
}
```
阅读全文