loops - C# Count Vowels -


i learning program c# , trying count vowels. getting program loop through sentence, instead of returning vowel count, returning length of string. appreciated.

    static void main()     {         int total = 0;          console.writeline("enter sentence");         string sentence = console.readline().tolower();          (int = 0; < sentence.length; i++)         {             if (sentence.contains("a") || sentence.contains("e") || sentence.contains("i") || sentence.contains("o") || sentence.contains("u"))             {                 total++;             }         }         console.writeline("your total number of vowels is: {0}", total);          console.readline();     } 

right now, you're checking whether sentence whole contains vowels, once each character. need instead check individual characters.

   (int = 0; < sentence.length; i++)     {         if (sentence[i]  == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')         {             total++;         }     } 

that being said, can simplify quite bit:

static void main() {     int total = 0;     // build list of vowels front:     var vowels = new hashset<char> { 'a', 'e', 'i', 'o', 'u' };      console.writeline("enter sentence");     string sentence = console.readline().tolower();      (int = 0; < sentence.length; i++)     {         if (vowels.contains(sentence[i]))         {             total++;         }     }     console.writeline("your total number of vowels is: {0}", total);      console.readline(); } 

you can simplify further if want use linq:

static void main() {     // build list of vowels front:     var vowels = new hashset<char> { 'a', 'e', 'i', 'o', 'u' };      console.writeline("enter sentence");     string sentence = console.readline().tolower();      int total = sentence.count(c => vowels.contains(c));     console.writeline("your total number of vowels is: {0}", total);     console.readline(); } 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -