【问题标题】:Count each character in a string计算字符串中的每个字符
【发布时间】:2022-07-08 00:58:44
【问题描述】:

我必须计算字符串中的字符,但我有点卡住了。如果输入数据为“test”,则结果为 t=2; e=1; s=1;依此类推。在我的代码中,结果是 t=1; e=1; s=1;而且我不知道如何才能正常工作。

Input data

测试

Output data   
t=2
e=1
s=1

这是我的代码

public static void Main()
{
    string text = Console.ReadLine();
    string distinctChars = GetDistinctChars(text);
    foreach (char c in distinctChars)
    {
        Console.WriteLine(c + " " + CountCharOccurrences(distinctChars, 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;
}

【问题讨论】:

  • 考虑使用字典来跟踪和保持计数。
  • 用这个方法增加字典?"CountCharOccurrences"
  • 您正在计算不同字符的计数 - 当然您得到 1
  • @gunr2171 不是真的

标签: c#


【解决方案1】:

这一行

       Console.WriteLine(c + " " + CountCharOccurrences(distinctChars, c));

应该是

       Console.WriteLine(c + " " + CountCharOccurrences(text , c));

有比你如何做更好的方法来做到这一点。使用 Dictionary 对象可能是最好的。然后你只需要循环一次原始文本。

【讨论】:

  • “更好的方法来做到这一点”他们可能还没有了解字典。恕我直言,这是一个很好的算法解决这个问题
猜你喜欢
  • 1970-01-01
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
  • 2022-10-15
  • 2012-06-04
  • 1970-01-01
相关资源
最近更新 更多