1

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;
}
4
  • 1
    Consider using a dictionary to track and keep counts. Commented Jul 7, 2022 at 16:53
  • increment the dictionary in this method?"CountCharOccurrences" Commented Jul 7, 2022 at 16:54
  • You are calculating the counts on the distinct chars - of course you get 1 Commented Jul 7, 2022 at 16:54
  • @gunr2171 not really Commented Jul 7, 2022 at 16:56

1 Answer 1

3

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. Then you only need to loop over the original text once.

Sign up to request clarification or add additional context in comments.

2 Comments

"better ways to do this" they probably haven't learnt about dictionaries yet. IMHO this is a nice algorithmic solution to this problem
@MongZhu -- exactly why I put it the way I did -- something to look forward to learning about on the journey

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.