谭浩强C++课后练习题2——统计字符各种类个数

谭浩强C++课后练习题2——统计字符各种类个数

题目描述:输入一行字符,分别统计出其中大写字母,小写字母,空格,数字和其他字符的个数。
算法思路:
用getline函数输入一个字符串,遍历整个字符串,判断字符的种类,让该种类字符的统计个数自增。

#include<iostream>
#include<string>
using namespace std;
int main() {
	string str;
	cout << "输入字符串:";
	getline(cin, str);
	int small = 0, big = 0, digit = 0, other = 0, space = 0;
	for (int i = 0;i < str.length();i++) {
		if (str[i] >= '0' && str[i] <= '9')
			digit++;
		else if (str[i] >= 'a' && str[i] <= 'z')
			small++;
		else if (str[i] >= 'A' && str[i] <= 'Z')
			big++;
		else if (str[i] == ' ')
			space++;
		else
			other++;
	}
	cout << "small=" << small << endl << "big=" << big << endl << "digit=" << digit << endl << "space=" << space << endl << "other=" << other << endl;
	return 0;
}

运行测试结果如下:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 35 · 访问量 639

猜你喜欢

转载自blog.csdn.net/weixin_45295612/article/details/105177814