Search code examples
c#stringvisual-studiocons

Counting vowel and consonant in a string


            int total = 0;
            int wordCount = 0, index = 0;
            var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
            var consonants = new HashSet<char> { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x' };

            for (int i = 0; i < sentence.Length; i++)

                    if (vowels.Contains(sentence[i]))
                    {
                        total++;
                    }
                    else if (consonants.Contains(sentence[i]))
                    {
                        total++;
                    }

                }
                Console.WriteLine("Your total number of vowels is: {0}", total);
                Console.WriteLine("Number of consonants: {0}", total);
                Console.ReadLine();
`

This is my code. When I run my code, it accurately tells me how many vowels there are, but it does not tell me the number of consonants. It just copied the number of vowels.


Solution

  •         int totalVowels = 0;
            int totalConsonants = 0;
            int wordCount = 0, index = 0;
            var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
            var consonants = new HashSet<char> { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x' };
    
            for (int i = 0; i < sentence.Length; i++)
            {
                    if (vowels.Contains(sentence[i]))
                    {
                        totalVowels++;
                    }
                    else if (consonants.Contains(sentence[i]))
                    {
                        totalConsonants++;
                    }
    
                }
                Console.WriteLine("Your total number of vowels is: {0}", totalVowels);
                Console.WriteLine("Number of consonants: {0}", totalConsonants);
                Console.ReadLine();