cplusplus写一个函数,统计字符串waht are you doing? 123456中字母,数字空格和其他字符的个数
时间: 2024-05-12 13:16:06 浏览: 8
好的,关于您的问题,我可以提供如下函数实现:
```c++
#include <iostream>
#include <ctype.h>
using namespace std;
void countCharacters(string str) {
int letters = 0, numbers = 0, spaces = 0, others = 0;
for (int i = 0; i < str.length(); i++) {
if (isalpha(str[i])) {
letters++;
}
else if (isdigit(str[i])) {
numbers++;
}
else if (isspace(str[i])) {
spaces++;
}
else {
others++;
}
}
cout << "Total letters: " << letters << endl;
cout << "Total numbers: " << numbers << endl;
cout << "Total spaces: " << spaces << endl;
cout << "Total other characters: " << others << endl;
}
int main() {
string str = "what are you doing? 123456";
countCharacters(str);
return 0;
}
```
通过该函数,可以统计出给定字符串中,字母、数字、空格以及其他字符的个数。希望这个解答对你有所帮助,如果您有其他问题,欢迎问我。