vc++编一函数,统计一个字符串中字母数字空格和其他字符的个数
时间: 2023-11-07 09:58:28 浏览: 41
好的,这是一个编程问题,我可以回答。以下是统计一个字符串中不同字符类型的个数的C++代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
void countCharacters(const char *str) {
int letter_cnt = 0, digit_cnt = 0, space_cnt = 0, other_cnt = 0;
for (int i = 0; i < strlen(str); i++) {
if (isalpha(str[i])) { // isalpha函数判断当前字符是否是字母
letter_cnt++;
} else if (isdigit(str[i])) { // isdigit函数判断当前字符是否是数字
digit_cnt++;
} else if (isspace(str[i])) { // isspace函数判断当前字符是否是空格
space_cnt++;
} else {
other_cnt++;
}
}
cout << "字母个数:" << letter_cnt << endl;
cout << "数字个数:" << digit_cnt << endl;
cout << "空格个数:" << space_cnt << endl;
cout << "其他字符个数:" << other_cnt << endl;
}
int main() {
char str[100];
cout << "请输入字符串:" << endl;
cin.getline(str, 100);
countCharacters(str);
return 0;
}
```
运行程序后,输入一个字符串,程序会统计该字符串中字母、数字、空格和其他字符的个数,并输出结果。希望我的回答能够帮助到您。