标签:文字 else ret std temp 字符 插入排序 英文字母 i++
输入一个字符串(其长度不超过81),分别统计其中26个英文字母出现的次数(不区分大、小写字母),并按字母出现次数从高到低排序,若次数相同,按字母顺序排列。字母输出格式举例,例如:A-3,表示字母A出现3次,C-0表示字母C没有出现。
输入:
第一行为输入,占一行,输入的字符串可能含有空格
输出:
第二行为输出,占一行。按照字母输出格式从高到低输出,各字母输出之间用一个空格字符分隔。
样例:
123abcAABXxwvUu+
A-3 B-2 U-2 X-2 C-1 V-1 W-1 D-0 E-0 F-0 G-0 H-0 I-0 J-0 K-0 L-0 M-0 N-0 O-0 P-0 Q-0 R-0 S-0 T-0 Y-0 Z-0
//插入排序法
#include<stdio.h>
#include<string.h>
int main()
{
char str[81] = "123abcAABXxwvUu+";
gets(str);
int letter_stat[26] = {0};
char letter[26] = { ‘ ‘ };
for (int i = 0; i < 26; i++)
{
letter[i] = i + ‘A‘;
}
int i = 0;
while (str[i])
{
int k = 0;
if (str[i] >= ‘A‘&&str[i] <= ‘Z‘)
{
k = str[i] - ‘A‘;
letter_stat[k]++;
}
else if (str[i] >= ‘a‘&&str[i] <= ‘z‘)
{
k = str[i] - ‘a‘;
letter_stat[k]++;
}
i++;
}
for (int i = 0; i < 26; i++)
{
int k = letter_stat[i];
int temp = letter[i];
int j = i - 1;
while (j >= 0 && letter_stat[j] < k)
{
letter_stat[j + 1] = letter_stat[j];
letter[j + 1] = letter[j];
j--;
}
letter_stat[j + 1] = k;
letter[j + 1] = temp;
}
for (int i = 0; i < 25; i++)
{
printf("%c-%d ", letter[i],letter_stat[i]);
}
printf("%c-%d", letter[25], letter_stat[25]);
return 0;
}
//冒泡排序法
#include<stdio.h>
#include<string.h>
int main()
{
char str[81] = "123abcAABXxwvUu+";
gets(str);
int letter_stat[26] = {0};
char letter[26] = { ‘ ‘ };
for (int i = 0; i < 26; i++)
{
letter[i] = i + ‘A‘;
}
int i = 0;
while (str[i])
{
int k = 0;
if (str[i] >= ‘A‘&&str[i] <= ‘Z‘)
{
k = str[i] - ‘A‘;
letter_stat[k]++;
}
else if (str[i] >= ‘a‘&&str[i] <= ‘z‘)
{
k = str[i] - ‘a‘;
letter_stat[k]++;
}
i++;
}
for (int i = 0; i < 25; i++)
for (int j = 0; j < 25 - i; j++)
{
if (letter_stat[j] < letter_stat[j + 1])
{
int temp = letter_stat[j + 1];
letter_stat[j + 1] = letter_stat[j];
letter_stat[j] = temp;
temp = letter[j + 1];
letter[j + 1] = letter[j];
letter[j] = temp;
}
}
for (int i = 0; i < 25; i++)
{
printf("%c-%d ", letter[i],letter_stat[i]);
}
printf("%c-%d", letter[25], letter_stat[25]);
return 0;
}
---------------------
标签:文字 else ret std temp 字符 插入排序 英文字母 i++
原文地址:https://www.cnblogs.com/ly570/p/11001433.html