C#统计字符串各字符出现次数时计数结果异常问题求助
字符统计功能Bug修复
问题现象
实现字符串每个字符出现次数统计功能时,输入test预期输出t=2、e=1、s=1,实际运行输出为t=1、e=1、s=1,结果不符合预期。
输入输出示例
- 输入
test
- 预期输出
t=2 e=1 s=1
错误原因
代码存在两处问题:
- 调用计数方法
CountCharOccurrences时,第一个参数错误传入了去重后的字符串distinctChars。去重后的字符串中每个字符仅出现1次,因此所有字符的统计结果都为1,应该传入原始输入字符串text作为统计源。 - 输出内容用空格拼接字符和计数,不符合要求的
=分隔格式。
修复后完整代码
public static void Main() { string text = Console.ReadLine(); string distinctChars = GetDistinctChars(text); foreach (char c in distinctChars) { Console.WriteLine(c + "=" + CountCharOccurrences(text, c)); } Console.ReadLine(); } private static int CountCharOccurrences(string text, char charToCount) { int count = 0; foreach (char c in text) { if (c == charToCount) { count++; } } return count; } private static string GetDistinctChars(string text) { string result = ""; foreach (char c in text) { if (result.IndexOf(c) == -1) { result += c; } } return result; }
内容的提问来源于stack exchange,提问作者BogdanNetan
相关产品推荐
相关产品推荐

