You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#统计字符串各字符出现次数时计数结果异常问题求助

字符统计功能Bug修复

问题现象

实现字符串每个字符出现次数统计功能时,输入test预期输出t=2、e=1、s=1,实际运行输出为t=1、e=1、s=1,结果不符合预期。

输入输出示例

  • 输入
test
  • 预期输出
t=2
e=1
s=1

错误原因

代码存在两处问题:

  1. 调用计数方法CountCharOccurrences时,第一个参数错误传入了去重后的字符串distinctChars。去重后的字符串中每个字符仅出现1次,因此所有字符的统计结果都为1,应该传入原始输入字符串text作为统计源。
  2. 输出内容用空格拼接字符和计数,不符合要求的=分隔格式。

修复后完整代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 20:15:52