0

hi so i am new to c# and i had a problem while i was trying to solve a little riddle: i need to find how many a-s are in a certain string.

    int anum = 0;
    string a = Console.ReadLine();
    for(int i = 0; i < a.Length; i++)
    {
        if (a[i] == "a")
        {
            anum++;
        }
    }
    Console.WriteLine(anum);

while i was solving it there was an error that i couldn't fix: '==' cannot be applied to operands of type 'char' and 'string' i tried googling it but it didnt help please help

  • 7
    `a[i]` is a `char`, not a `string`. Use `a[i] == 'a'`. – 41686d6564 stands w. Palestine Jun 05 '21 at 12:58
  • A string is a sequence of characters (CHAR). so what you are trying to do is compare an array with an element. for your solution, use single quotes to wrap character literal ie. `a[i] == 'a'` – RohitS Jun 05 '21 at 13:05
  • 1
    Does this answer your question? [How would you count occurrences of a string (actually a char) within a string?](https://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-actually-a-char-within-a-string) and [Count a specific letter in a string](https://stackoverflow.com/questions/28826110/count-a-specific-letter-in-a-string) –  Jun 05 '21 at 13:07

1 Answers1

1

You can use (') instead of (")

if (a[i] == 'a')
{
      anum++;
}

As a is a character and the (") are being used for strings