Search code examples
c#foreachcountchars

Can I use: "TextEntered.ToUpperInvariant().Contains("a")" to count chars in a string?


I'm trying to count vowels in a certain string inputted by a user. So if there are 6 A's in a sentence that the user inputs via a console.Readline(); the console should return A=6. The final output is supposed to look a bit like:

A =?  
I =?  
E =?  
O =?  
U =?

Note the ?'s are representative of the number of vowels detected in the string.

I have a few ideas and a step by step, for example "textEntered.ToUpperInvariant().Contains("a")" as mentioned in the title. Would this work? I've been told this may just return true every time that a vowel is detected. If so, could I set true in such a way that it increments the count?

I have also tried to find a solution on https://www.dotnetperls.com/count-characters but this doesn't seem to have the desired output.

I think the best way would be to use a foreach loop in some way to loop the character search!

If not, what is the most efficient way to code this? Thanks! (please bare in mind that I'm a student still getting to grips with the language, please be kind!)


Solution

  • You could use Count:

    int countOfA = textEntered.Count(x => x == 'a');
    

    EDIT:

    int countOfA = textEntered.ToUpper().Count(x => x == 'A');