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; e=1; s=1; and so on.In my code, the result is t=1; e=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;
}