【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();
        }

    }

猜你喜欢

转载自blog.csdn.net/yf391005/article/details/83620942
今日推荐