编写一个函数,由实参传来一个字符串,统计此字符串中字母,数字,空格和其他字符的个数,在主函数中输入字符串以及输出上述结果
时间: 2024-04-27 11:04:34 浏览: 12
好的,我可以帮你编写这个函数。以下是代码实现:
```
#include <iostream>
#include <string>
using namespace std;
void countChars(string str)
{
int letters = 0, digits = 0, spaces = 0, others = 0;
for (int i = 0; i < str.length(); i++)
{
if (isalpha(str[i])) //判断是否是字母
{
letters++;
}
else if (isdigit(str[i])) //判断是否是数字
{
digits++;
}
else if (isspace(str[i])) //判断是否是空格
{
spaces++;
}
else //其他字符
{
others++;
}
}
cout << "字母个数:" << letters << endl;
cout << "数字个数:" << digits << endl;
cout << "空格个数:" << spaces << endl;
cout << "其他字符个数:" << others << endl;
}
int main()
{
string str;
cout << "请输入一个字符串:";
getline(cin, str);
countChars(str);
return 0;
}
```
你可以在主函数中调用 `countChars` 函数并传入一个字符串参数,该函数会统计此字符串中字母,数字,空格和其他字符的个数,并输出结果。
如果你有任何其他问题,可以继续问我。