字典实现判断一个字符串中某个字母出现的次数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            //用字典实现判断一个字符串中某个字母出现的次数
            string str = "welcome to china!";
            Dictionary<char, int> dic = new Dictionary<char, int>();

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i]==' ')
                {
                    continue;
                }
                if (dic.ContainsKey(str[i]))
                {
                    dic[str[i]]++;
                }
                else
                {
                    dic[str[i]] = 1;
                }
            }

            foreach (KeyValuePair<char,int> kv in dic)
            {
                Console.WriteLine("{0}重复出现{1}次",kv.Key,kv.Value);
            }
            Console.ReadKey();
        }
    }
}

 

posted @ 2016-07-31 19:07  kennyhip  阅读(365)  评论(0)    收藏  举报