简体   繁体   中英

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!)

You could use Count:

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

EDIT:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM