C#遍历字符串统计字符时如何跳过已处理字符避免重复计数
问题描述
编写findChar()函数用于遍历字符串统计指定字符的出现次数(不区分大小写),例如统计字符串"Cincinnati"的字符频次(C共出现2次、i共出现3次等),但当前逻辑遇到已统计过的字符(如重复出现的'C'、'i')时,会重复返回对应统计值。
原有问题代码如下:
public static int findChar(string name, char c) { int count = 0; for (int i = 0; i < name.Length; i++) { if (name[i] == c || name[i] == Char.ToUpper(c) || name[i] == Char.ToLower(c)) { count++; } } return count; } static void Main(string[] args) { string name = "Cincinnati"; char c = ' ' ; int count = 0; for (int i = 0; i < name.Length; i++) { c = name[i]; count = findChar(name, c); Console.WriteLine(count); } }
运行现状
当前程序运行输出为:
2 3 3 2 3 3 3 1 1 3
预期目标
跳过已统计过的字符,仅输出首次遇到字符的对应计数,预期输出:
2 3 3 1 1
问题根因
- Main方法遍历字符串每一位字符时,没有做已统计字符的去重判断,所有字符(包括重复出现的同字母大小写变体)都会触发计数计算和输出逻辑,导致结果重复。
findChar内的大小写判断逻辑存在冗余:name[i] == c本身已经覆盖了字符完全匹配的场景,额外判断转大/小写的逻辑重复,且没有统一比较基准,存在判断漏判风险。
修复方案
- 优化
findChar的比较逻辑:将传入的目标字符和遍历到的字符串字符统一转为小写(或大写)后比较,简化判断条件,避免冗余。 - 在Main方法中新增哈希集合,记录已经统计过的字符(统一转小写/大写存储,实现大小写不敏感的去重);遍历到当前字符时,先判断是否已经统计过,已统计则直接跳过,未统计则计算计数、输出结果,再将字符加入已统计集合。
修复后完整代码:
public static int findChar(string name, char c) { int count = 0; // 统一把目标字符转小写作为比较基准 char targetLower = Char.ToLower(c); for (int i = 0; i < name.Length; i++) { // 遍历到的字符也转小写后比较,逻辑更简洁 if (Char.ToLower(name[i]) == targetLower) { count++; } } return count; } static void Main(string[] args) { string name = "Cincinnati"; // 用哈希集合存已经统计过的字符(统一存小写格式,实现大小写不敏感去重) HashSet<char> countedChars = new HashSet<char>(); for (int i = 0; i < name.Length; i++) { char currentLower = Char.ToLower(name[i]); // 已经统计过的字符直接跳过 if (countedChars.Contains(currentLower)) { continue; } // 未统计的字符才计算计数、输出、标记为已统计 int count = findChar(name, name[i]); Console.WriteLine(count); countedChars.Add(currentLower); } }
运行修复后的代码,即可得到预期的输出结果。
内容的提问来源于stack exchange,提问作者dmullad
相关产品推荐
相关产品推荐

