c#把一个字符串,按每个字母作为key,出现的次数作为value形成一个字典的代码
2025-02-17 18:29 钟铧若岩 阅读(18) 评论(0) 收藏 举报using System; using System.Collections.Generic; class Program { static void Main() { string input = "hello world"; Dictionary<char, int> letterCount = CountLetters(input); // 输出结果 foreach (KeyValuePair<char, int> pair in letterCount) { Console.WriteLine($"字母 '{pair.Key}' 出现了 {pair.Value} 次。"); } } static Dictionary<char, int> CountLetters(string input) { Dictionary<char, int> letterCount = new Dictionary<char, int>(); // 遍历字符串中的每个字符 foreach (char c in input) { if (letterCount.ContainsKey(c)) { // 如果字典中已经包含该字符,则将其计数加 1 letterCount[c]++; } else { // 如果字典中不包含该字符,则将其添加到字典中,并将计数初始化为 1 letterCount.Add(c, 1); } } return letterCount; } }
使用lamda实现
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { string input = "hello world"; // 使用 Lambda 表达式和 LINQ 统计字符出现次数 var letterCount = input.GroupBy(c => c) .ToDictionary(g => g.Key, g => g.Count()); // 输出结果 foreach (var pair in letterCount) { Console.WriteLine($"字母 '{pair.Key}' 出现了 {pair.Value} 次。"); } } }
浙公网安备 33010602011771号