繁体   English   中英

计算字符串中的每个字符

[英]Count each character in a string

我必须计算字符串中的字符,我有点卡住了。 如果输入数据为“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;
}

这条线

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

应该

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM