[英]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.