做畢設時,需要統計漢語語料庫中單詞(單詞已經粗切分)出現的頻率,想到與我們開始學習C語言時統計字符串中每個字符出現的個數類似,就想用C#實現一下,發現泛型集合類Dictionary很有用,幾行代碼就搞定,爽!
1 private static void FnCountWord()
2 {
3 String text = Console.ReadLine();
4 Dictionary<Char, int> charDict = new Dictionary<char, int>();
5 for (int i = 0; i < text.Length; i++)
6 {
7 if (charDict.ContainsKey(text[i]) == true)
8 {
9 charDict[text[i]]++;
10 }
11 else
12 {
13 charDict.Add(text[i], 1);
14 }
15 }
16 //int編號,KeyValuePair<Char, int>中char字符,int統計字符數量
17 Dictionary<int, KeyValuePair<Char, int>> charID = new Dictionary<int, KeyValuePair<Char, int>>();
18 int k = 0;
19 foreach (KeyValuePair<Char, int> charInfo in charDict)
20 &