统计字符串中字母、数字、空格和其他字符的个数C++
时间: 2023-07-10 09:42:37 浏览: 86
可以通过遍历字符串,判断每个字符的ASCII码值来统计字母、数字、空格和其他字符的个数。以下是一个简单的C++代码示例:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello, 123!";
int letterCount = 0;
int digitCount = 0;
int spaceCount = 0;
int otherCount = 0;
for (int i = 0; i < str.length(); i++)
{
char c = str[i];
if (isalpha(c)) // 判断是否为字母
{
letterCount++;
}
else if (isdigit(c)) // 判断是否为数字
{
digitCount++;
}
else if (isspace(c)) // 判断是否为空格
{
spaceCount++;
}
else // 其他字符
{
otherCount++;
}
}
cout << "Letter count: " << letterCount << endl;
cout << "Digit count: " << digitCount << endl;
cout << "Space count: " << spaceCount << endl;
cout << "Other count: " << otherCount << endl;
return 0;
}
```
输出结果为:
```
Letter count: 7
Digit count: 3
Space count: 1
Other count: 2
```
阅读全文