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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值