C++ 字符串统计 - 字母、数字、空格和其他字符
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int letter = 0, digit = 0, space = 0, other = 0; // 初始化各种字符的个数为0
cout << '请输入字符串:';
getline(cin, str); // 读取整行字符串,包括空格
for (int i = 0; i < str.length(); i++)
{
if (isalpha(str[i])) // 判断是不是字母
letter++;
else if (isdigit(str[i])) // 判断是不是数字
digit++;
else if (isspace(str[i])) // 判断是不是空格
space++;
else // 其它字符
other++;
}
cout << '字母个数:' << letter << endl;
cout << '数字个数:' << digit << endl;
cout << '空格个数:' << space << endl;
cout << '其它字符个数:' << other << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/ouat 著作权归作者所有。请勿转载和采集!