1. 程式人生 > >【C#基礎 】Dictionary 統計字串中每個字母出現的次數

【C#基礎 】Dictionary 統計字串中每個字母出現的次數

class Program
    {
        static void Main(string[] args)
        {
            // 其實hello world的字母個數還是挺多的呢
            string str = "hello world";
            //建立一個字典
            Dictionary<char, int> dic = new Dictionary<char, int>();
            //字串可以看作一個字元陣列,
            foreach (char item in str)
            {
                // 如果item是字母的話
                if (char.IsLetter(item))
                {
                    // 如果這個字母在dictionary中沒有,
                    if (!dic.ContainsKey(item))
                    {
                        // 那麼為這個字母新新增一個鍵值對,它的值是1
                        dic.Add(item, 1);
                    }
                    else
                    {
                        // 如果這個字母在鍵中有了,那麼給該鍵的值+1
                        dic[item]++;                        
                    }
                }
            }
            // 遍歷字典
            foreach (KeyValuePair<Char, int> item in dic)
            {
                Console.WriteLine(item.Key + " " + item.Value);               
            }
            Console.ReadKey();
        }

    }