C#中的字串統計排序之dictionary例項應用
問題:
給出一個字串,字串為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); } } } } }