计算每个字符出现的次数(两种方法)

来源:互联网 发布:福彩3d开奖数据下载 编辑:程序博客网 时间:2024/05/18 02:39

 

 

#region Dictionary 计算每个字符出现的次数
            //string str = "Welcome to Chinaworld";
            //str = str.ToUpper();
            //Dictionary<char, int> dic = new Dictionary<char, int>();
            //for (int i = 0; i < str.Length; i++)
            //{
            //    if (char.IsLetter(str[i]) == true)
            //    {
            //        if (dic.Keys.Contains(str[i]))
            //        {
            //            dic[str[i]]++;
            //        }
            //        else
            //        {
            //            dic[str[i]] = 1;
            //        }
            //    }

            //}
            //foreach (KeyValuePair<char, int> item in dic)
            //{
            //    Console.WriteLine("{0}{1}", item.Key, item.Value);
            //}
            #endregion

#region Hashtable 计算每个字符出现的次数
            int numb1;
            string str = "Welcome to Chinaworld";
            str = str.ToUpper();
            Hashtable table = new Hashtable();
            for (int i = 0; i < str.Length; i++)
            {
                if (char.IsLetter(str[i]) == true)
                {
                    if (table.ContainsKey(str[i]))
                    {
                        numb1 = Convert.ToInt32(table[str[i]]);
                        numb1++;
                        table[str[i]] = numb1;
 
                    }
                    else
                    {
                        numb1 = Convert.ToInt32(table[str[i]]);
                        numb1=1;
                        table[str[i]] = numb1;
                    }
                }
            }
            foreach (DictionaryEntry item in table)
            {
                Console.WriteLine("{0}{1}", item.Key, item.Value);
            }    
           
            #endregion

0 0
原创粉丝点击