PTA刷题Basic篇——1042.字符统计——Day(21)

问题描述

在这里插入图片描述
统计出句子中出现最多的英文字符(将大写字母当作小写字母)

题目分析

题目很简单,我们直接写过一篇文章讲过toupper()这个函数,它是一个在ctype中定义的函数,这道题使用一个类似的函数,tolower()。
由于这个字符串中有大量的空格,所以我们不能简单地通过cin读取,使用getline可以将空格一起读入,且遇到回车会中断。
首先我们声明一个计数数组count,初始化为0.在字符串中进行遍历,将字母通过tolower()全部变为小写字母,找到其对应的ASCII码值作为索引,将计数数组count的对应位置+1。然后依次只在[97,125)的区间进行查找,找出最大值,如果有并列返回最小的索引对应的字母。

代码

#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
int main()
{       
	string s;   
	int count[210] = {0};    
	int max = 0;    
	int min = 300;    
	getline(cin,s);    
	for(int i = 0;i < s.length();i++)   
	{        
		count[tolower(s[i])]++;     
	}    
	for(int i = 97;i < 124;i++)    
	{        
		if(count[i] > max)        
		{            
			max = count[i];            
			min = i;        
		}    
	}    	
	cout<<char(min)<<" "<<max;    
	return 0;
}

答题用时12min
Q42——finish√

原创文章 101 获赞 13 访问量 2329

猜你喜欢

转载自blog.csdn.net/weixin_44755413/article/details/105810606