问题:
给出一个字符串,字符串为26个英文大写字母,要求统计出每个大写字母出现的次数并且排序。
解答:这里我想的是先创建一个int型数组值都为0,一个char型数组为26个字母,先遍历字符串,然后套一层for循环遍历是否出现了某个字母,如果有,则对应的int数组计数自增。最后得出的是int数组中存的是字母出现的个数,然后用键值对把两个数组保存起来,通过字典来排序。
(本来对字典不是很熟悉,测试发现Key必须唯一)所以:Dictionary<char, int> dic = new Dictionary<char, int>();
而不能Dictionary<int, char> myDic = new Dictionary<int, char>();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 字母统计排序
{
class Program
{
static void Main(string[] args)
{
string str = "FASHWERIUYQWERIOPWEURIPOFASDIOPWEUQRPOIUASDOPIWEUQRIOPWRQEUQWOPREQRHWEPOQWRHEOPIRHWPEQIO";
char[] charArray = str.ToCharArray();
CountLetter(charArray);
Console.ReadKey();
}
static void CountLetter(char[] charArray) {
//键值对
//List<KeyValue> list = new List<KeyValue>();
Dictionary<char, int> dic = new Dictionary<char, int>();
Dictionary<int, char> myDic = new Dictionary<int, char>();
//用数组统计出现次数
int[] count = new int[26];
for (int i = 0; i < count.Length; i++)
{
count[i] = 0;
}
//26个英文字母
char[] letter = new char[26];
int n = 0;
for (char i = 'A'; i <= 'Z'; i++) {
letter[n] = i;
n++;
}
//统计次数
for (int i = 0; i < charArray.Length; i++) {
for (int j = 0; j < letter.Length; j++) {
if (charArray[i] == letter[j]) {
count[j]++;
}
}
}
//将字母和出现的次数以键值对的形式保存下来
for (int i = 0; i < letter.Length; i++) {
//list.Add(new KeyValue(count[i], letter[i]));
dic.Add(letter[i], count[i]);
//myDic.Add(count[i], letter[i]);
}
//将字典中的出现次数排序
//Dictionary<char, int> newDic = dic.OrderBy(p => p.Value).ToDictionary(p => p.Key, p => p.Value);
Dictionary<char, int> newDic = dic.OrderByDescending(p => p.Value).ToDictionary(p => p.Key, p =>p.Value);
//Dictionary<int, char> myNewDic = myDic.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
//输出结果
foreach (var i in newDic) {
if (i.Value != 0) {
Console.WriteLine(i.Value + ":"+i.Key);
}
}
}
}
}