1. 利用Dictionary 將英文單字與數量分別用Key,Value表示
2. 判斷字母大小寫
3. 改用SortedDictionary 自動遞增排序
請看範例 :
- //判斷字串內有幾個單字
- static SortedDictionary<char,int> CountWord(string text)
- {
- SortedDictionary<char, int> Dic = new SortedDictionary<char, int>();
- char[] words = text.ToCharArray();
- foreach (char word in words)
- {
- //去除非字母
- if (char.IsLetter(word))
- {
- //轉小寫
- char w = char.ToLower(word);
- if (Dic.ContainsKey(w))
- {
- Dic[w]++;
- }
- else
- {
- Dic[w] = 1;
- }
- }
- }
- return Dic;
- }
- ///Ditionary 練習從片語中判斷出現幾次單字
- string text = @"Do you like green eggs and ham?
- i do not like them, Sam-I-AM";
- SortedDictionary<char, int> frequency = CountWord(text);
- foreach (KeyValuePair<char,int> word in frequency)
- {
- char key = word.Key;
- int value = word.Value;
- Console.WriteLine("{0} : {1}個", key, value);
- }
參考資料 : 精通C#
沒有留言:
張貼留言