任何疑问、意见、建议请留言公众号:一航代码
从键盘输入一行英文句子,句子中只有英文单词和空格,每个单词之间用若个空格隔开,英文单词由大小写字母组成,编程完成以下任务:
(1)统计并输出此句子中英文字母的个数;(10分)
(2)统计并输出此句子中单词的个数;(10分)
(3)查找此句子中出现次数最多的字母(不区分大小写,大小写字母是相同的)及次数。当出现最多的字符不止一个时,都能找到,并输出找到的所有字母及次数。(输出字母时大小写均可) (20分)
输入格式:
输入只有一行句子。仅有空格和英文字母构成,末尾以回车作为结束。(不超过1000个字符)
输出格式:
在接下来的每一行分别输出字母个数、单词个数、出现次数最多的字符(不止一个则用空格隔开)、出现的次数。
输入样例:
This is An Pencil Case
输出样例:
18
5
i s
3
解决方法:
(1)算法的基本思想:
1.使用while和cin对句子中的单词循环读入存入字符串数组,数组长度即为单词个数,题目要求回车结束,需要进行判断。
2.遍历每个单词,将大写字母转换为小写字母,用count数组计数,字符总个数为count之和,出现次数最多的字符为count数组中最大的下标值(ASCII值),最多的次数为count值。
3.出现次数最多的字符不止一个时注意最后一个字符单独拿出来连接回车输出。
(2)代码实现:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
int main()
{
vector<string> words; //存单词,vector长度即单词个数
vector<int> count(130, 0); //英文字母的最大ASCII值不超过122,记住小写a为97,再加26-1得z为122
string word;
while ((cin >> word)) //使用while和cin组合循环读入字符串以回车结束在后面加一个getchar
{
char c = getchar();
for (int i = 0; i < word.size(); i++)
{
count[tolower(word[i])]++; //将字符全部转换为小写,并以ascii值为下标,数组值为出现次数计数
}
words.push_back(word);
if (c == '\n') //判断回车
{
break;
}
}
vector<char> res; //出现次数最多的字符数组
int max_num_of_ch = 0; //最大出现次数
int num_of_ch = 0;
for (int i = 0; i < count.size(); i++)
{
if (count[i] != 0) //字符出现
{
num_of_ch += count[i];
if (count[i] > max_num_of_ch) //当前字符出现次数最多
{
vector<char>().swap(res); //清空字符数组
res.push_back(i); //将当前字符push进数组
max_num_of_ch = count[i];
}
else if (count[i] == max_num_of_ch)//如果多个字符出现次数相等,push进数组
{
res.push_back(i);
}
}
}
cout << num_of_ch << endl;
cout << words.size() << endl;
for (int i = 0; i < res.size() - 1; i++)
{
cout << res[i] << ' '; //输出多个字符,以空格隔开。循环到size-1
}
cout << res[res.size() - 1] << endl; //最后一个字符连接回车输出
cout << max_num_of_ch << endl;
system("pause");
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
int hashtable[26] = {0}; //统计各个小写字母出现次数
int cnt_alpha = 0, cnt_word = 0, MAX = -1;
int main()
{
string str;
while (cin >> str)
{
cnt_alpha += str.size(); //统计字母个数
cnt_word++; //统计英文单词个数
for (int i = 0; i < str.size(); ++i)
{ //转小写字母,统计各个小写字母出现次数
str[i] = tolower(str[i]);
hashtable[str[i] - 'a']++;
MAX = max(MAX, hashtable[str[i] - 'a']); //记录字母最大出现次数
}
char ch = getchar(); //结束死循环,新技能get
if (ch == '\n')
{
break;
}
}
printf("%d\n", cnt_alpha); //输出字母的个数
printf("%d\n", cnt_word); //输出英文单词的个数
int flag = 0;
for (int i = 0; i < 26; ++i)
{ //输出出现次数最多的小写字母
if (hashtable[i] == MAX)
{
if (flag == 0)
{
printf("%c", i + 'a');
flag = 1;
}
else
printf(" %c", i + 'a');
}
}
printf("\n%d", MAX); //输出最大出现次数
return 0;
}