统计字符串中每个字符出现了多少次Directory

 static void Main(string[] args)
        {
            string s = "this is a test";
            Dictionary<char, int> dict = GetCharCount(s);
            //foreach (KeyValuePair<char, int> v in dict)
            foreach (var v in GetCharCount(s))
            {
                Console.WriteLine("Key:{0},Value:{1}", v.Key, v.Value);
            }
        }

        public static Dictionary<char, int> GetCharCount(string str)
        {
            Dictionary<char, int> dict = new Dictionary<char, int>();
            foreach (char c in str)
            {
                if (dict.ContainsKey(c))
                {
                    dict[c] += 1;
                }
                else
                {
                    dict[c] = 1;
                }
            }

            return dict;
        }
View Code

 

posted @ 2013-04-29 22:50  Binyao  阅读(143)  评论(0)    收藏  举报