【发布时间】: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#