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

如何避免数组存储重复字符?字符出现次数统计代码问题排查

问题分析与解决方案

首先咱们来拆解下你代码里的核心问题,再给出针对性的修复方案:

1. storing数组的Contains方法失效的原因

你在每一轮循环内部都重新创建了storing数组:

char[] storing = new char[array.Length];

这意味着每一次循环的storing都是全新的空数组(所有元素默认值是'\0'),所以storing.Contains<char>(array[i])永远返回false——数组里根本没有你要检查的目标字符,自然起不到“判断是否已统计过”的作用。

2. 重复统计字符的问题

你的嵌套循环逻辑会导致同一个字符被多次统计:比如输入"aaa",i=0时会统计到3次a,i=1时又会统计到2次a,i=2时统计到1次a,最终会重复输出三次a的次数,这显然不是你想要的结果。


解决方案一:用HashSet<char>跟踪已处理字符(修正原有逻辑)

我们把storing换成HashSet<char>(它天生适合做存在性检查,还能自动去重),并把它放在循环外面,这样就能持续跟踪已经统计过的字符:

static void Main(string[] args)
{
    Console.WriteLine("Enter any string");
    string msg = Console.ReadLine();
    if (string.IsNullOrEmpty(msg))
    {
        Console.WriteLine("Empty string entered!");
        return;
    }

    char[] array = msg.ToCharArray();
    HashSet<char> processedChars = new HashSet<char>(); // 存储已统计过的字符

    for (int i = 0; i < array.Length; i++)
    {
        char currentChar = array[i];
        // 如果已经统计过该字符,直接跳过
        if (processedChars.Contains(currentChar))
        {
            Console.WriteLine($"{currentChar} already counted");
            continue;
        }

        // 统计当前字符的总出现次数
        int count = 0;
        for (int j = 0; j < array.Length; j++)
        {
            if (array[j] == currentChar)
            {
                count++;
            }
        }

        // 标记该字符已处理
        processedChars.Add(currentChar);
        Console.WriteLine($"{currentChar} comes {count} times");
    }
}

解决方案二:用Dictionary<char, int>直接统计(更简洁高效)

如果不想写嵌套循环,用Dictionary<char, int>可以一步完成统计和去重,代码更简洁,效率也更高(只需要遍历字符串一次):

static void Main(string[] args)
{
    Console.WriteLine("Enter any string");
    string msg = Console.ReadLine();
    if (string.IsNullOrEmpty(msg))
    {
        Console.WriteLine("Empty string entered!");
        return;
    }

    Dictionary<char, int> charCount = new Dictionary<char, int>();

    foreach (char c in msg)
    {
        if (charCount.ContainsKey(c))
        {
            charCount[c]++;
        }
        else
        {
            charCount[c] = 1;
        }
    }

    // 输出最终统计结果
    foreach (var pair in charCount)
    {
        Console.WriteLine($"{pair.Key} comes {pair.Value} times");
    }
}

额外优化建议

  • 增加空字符串判断,避免后续代码出现异常;
  • 如果需要忽略大小写(比如把'A'和'a'视为同一个字符),可以在统计时统一转换:char.ToLower(c);
  • HashSet和Dictionary都是C#中专门处理去重、键值对统计的集合,比手动用数组处理高效得多,也更不容易出错。

内容的提问来源于stack exchange,提问作者JAWAD KHAN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:44:00