C#统计字符串数组高频词及元音总数代码运行异常问题排查
C#代码问题修复说明
- 语法错误:代码中多处Console.WriteLine的字符串直接换行,不符合C#语法规范,编译会报错
- 元音统计模块存在你怀疑的string与char逻辑错误:当前遍历的
arr[i]是输入的每个完整单词(string类型),直接和"a"这类单字符字符串做相等判断,只有当整个单词是单个小写元音字母时才会计数,完全达不到统计所有单词内元音字母总数的要求 - 未覆盖大小写元音:大写的A、E、I、O、U不会被识别为元音
- 辅音统计逻辑完全错误:当前是把不符合元音判断的整个单词计为1个辅音,实际应该统计所有单词中不属于元音的字母数量
- 高频单词统计边界提示:如果有多个单词出现频率同为最高,当前代码只会返回遍历字典时第一个遇到的高频单词,可根据实际需求调整返回规则
修复后完整代码
using System; using System.Collections.Generic; namespace lab1._2 { class Program { static String findWord(String[] arr) { Dictionary<String, int> hs = new Dictionary<String, int>(); for (int i = 0; i < arr.Length; i++) { if (hs.ContainsKey(arr[i])) { hs[arr[i]] = hs[arr[i]] + 1; } else { hs.Add(arr[i], 1); } } String key = ""; int value = 0; foreach (KeyValuePair<String, int> me in hs) { if (me.Value > value) { value = me.Value; key = me.Key; } } return key; } static void Main(string[] args) { int s; Console.WriteLine("Enter size of array : "); s = Convert.ToInt32(Console.ReadLine()); string[] arr = new string[s]; Console.WriteLine("Enter string elements : "); for (int i = 0; i < s; i++) { arr[i] = Console.ReadLine(); } Console.WriteLine("\nArray elements : "); for (int i = 0; i < s; i++) { Console.WriteLine(arr[i]); } Console.WriteLine("\nThe most frequent word : "); Console.WriteLine(findWord(arr)); // 修复元音辅音统计逻辑 int vowel = 0, cons = 0; HashSet<char> vowels = new HashSet<char> {'a','A','e','E','i','I','o','O','u','U'}; for (int i = 0; i < arr.Length; i++) { // 遍历每个单词的所有字符 foreach (char c in arr[i]) { if (vowels.Contains(c)) { vowel++; } else { cons++; } } } Console.WriteLine("Vowels : "); Console.WriteLine(vowel); Console.WriteLine("Consants : "); Console.WriteLine(cons); } } }
内容的提问来源于stack exchange,提问作者Alex Alecco
相关产品推荐
相关产品推荐

