计算字符串中出现字符的次数

来源:互联网 发布:最好的网络加速器 编辑:程序博客网 时间:2024/06/02 12:21

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

namespace lianxi4
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Welcome to china! this is a beautiful county, i think you will like it.here is The great wall";
           str= str.ToLower();//避免出现大小写问题,将字符串全都变成小写
            Dictionary<char, int> dic = new Dictionary<char, int>();//实例化一个字典类对象,<键,值>
            for (int i = 0; i < str.Length;i++ )//便利字符串通过键(str[i])找值的方法将相同的加起来给值
            {
                if (char.IsLetter(str[i]))//只允许是字符
                {//是字符才可进入条件,空格、符号不能进入;str[i]是键
                    if (dic.ContainsKey(str[i]))//当前这个字符,包含在dic中时就累加
                    {
                        dic[str[i]]++;//根据键找值,让值自加记录个数
                    }
                    else { dic.Add(str[i], 1); }//如果不包含当前的就为一
                }
            }
            foreach (KeyValuePair<char, int> kv in dic)//定义个字典类型遍历输出dic的键和值
            {
                Console.WriteLine("字符{0},{1}个", kv.Key, kv.Value);
            }
            Console.ReadKey();
        }
    }
}