0

I want to count a particular character as shown in the code

but it seems to be case-sensitive. Can anyone tell me what is wrong with the code? Thanks

class ClassTwo
{
    public static void Main(String[] args)
    {
        ClassTwo ct = new ClassTwo();
        Console.WriteLine(ct.GetCountLetters("canada", 'A'));
    }

    int GetCountLetters(string text, char c)
    {
        int count = 0;
        text = text.ToLowerInvariant();
        char[] chars = text.ToCharArray();    // 'c'  'a'  'n'  'a' 'd' 'a'
        for (int i = 0; i < chars.Length; i++)
        {
            if (chars[i] == c)
            {
                count++;
            }
        }
        return count;
    }
}
  • 3
    You're lowering the text but passing a cap char. What do you *need* it to do? – ChiefTwoPencils Aug 17 '22 at 18:04
  • Yes, character comparisons are case-sensitive. A simple fix would be `if (chars[i] == c.ToLowerInvariant())` – D Stanley Aug 17 '22 at 18:14
  • Thanks, a lot! @ D Stanley for the idea Now, here is the working one: if (chars[i] == char.ToLowerInvariant(c)) { count++; } – MD EMRUL EMRAN Aug 17 '22 at 18:25
  • Side note: it might be useful to pull the `ToLowerInvariant()` calls out of `GetCountLetters` so that the caller can determine how it should be compared. Also, you can simplify that a lot with: `text.Count(x => x == c);` – ChiefTwoPencils Aug 17 '22 at 19:29

0 Answers0