统计字符串中字母、数字、空格和其他字符的个数C++
时间: 2023-11-19 21:04:27 浏览: 100
统计字符串中数字、字母和空格的个数
5星 · 资源好评率100%
可以使用C++中的isdigit()、isalpha()和isspace()函数来判断字符是否为数字、字母和空格,其他字符可以通过排除这些情况来计算。以下是一个示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello World! 123";
int letter_count = 0, digit_count = 0, space_count = 0, other_count = 0;
for (int i = 0; i < str.length(); i++)
{
if (isalpha(str[i]))
letter_count++;
else if (isdigit(str[i]))
digit_count++;
else if (isspace(str[i]))
space_count++;
else
other_count++;
}
cout << "Letter count: " << letter_count << endl;
cout << "Digit count: " << digit_count << endl;
cout << "Space count: " << space_count << endl;
cout << "Other count: " << other_count << endl;
return 0;
}
```
输出:
```
Letter count: 10
Digit count: 3
Space count: 3
Other count: 2
```
阅读全文