[英]Count each character in a string
I have to count character in a string and i'm a little stuck.我必须计算字符串中的字符,我有点卡住了。 If input data is "test", the result will be t=2;如果输入数据为“test”,则结果为 t=2; e=1; e=1; s=1; s=1; and so on.In my code, the result is t=1;依此类推。在我的代码中,结果是 t=1; e=1; e=1; s=1; s=1; and i don't know how to make to work correctly.而且我不知道如何使其正常工作。
Input data
test测试
Output data
t=2
e=1
s=1
Here is my code这是我的代码
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;
}
This line这条线
Console.WriteLine(c + " " + CountCharOccurrences(distinctChars, c));
should be应该
Console.WriteLine(c + " " + CountCharOccurrences(text , c));
There are better ways to do this than how you are doing it.有比你如何做更好的方法来做到这一点。 Using a Dictionary object is probably the best.使用 Dictionary 对象可能是最好的。 Then you only need to loop over the original text once.然后你只需要循环一次原始文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.