首页 > 代码库 > 输入字符串,判断每个字符串出现多少次
输入字符串,判断每个字符串出现多少次
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace msdemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入一段字符串");
string sentences = Console.ReadLine();
sentences = sentences.ToLower();
Dictionary<char, int> dict = new Dictionary<char, int>();
char[] chs = sentences.ToCharArray();
for (int i = 0; i < chs.Length; i++)
{
if (!dict.ContainsKey(chs[i]))
{
dict.Add(chs[i], 1);
}
else
{
dict[chs[i]]++;
}
}
Console.WriteLine("未排序之前");
foreach (KeyValuePair<char, int> kv in dict)
{
Console.WriteLine("字母:{0}出现了{1}次。", kv.Key, kv.Value);
}
Console.WriteLine("排序之后");
Dictionary<char, int> dict1 = dict.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
foreach (KeyValuePair<char, int> kv in dict1)
{
Console.WriteLine("字母:{0}出现了{1}次。", kv.Key, kv.Value);
}
Console.Read();
}
}
}
输入字符串,判断每个字符串出现多少次