Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Count Vowels

I am learning to program C# and I am trying to count the vowels. I am getting the program to loop through the sentence, but instead of returning vowel count, it is just returning the length of the string. Any help would be greatly appreciated.

    static void Main()
    {
        int total = 0;

        Console.WriteLine("Enter a Sentence");
        string sentence = Console.ReadLine().ToLower();

        for (int i = 0; i < 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();
    }
like image 640
Phorden Avatar asked Aug 07 '13 17:08

Phorden


7 Answers

Or with linq.

static void Main()
    {
        int total = 0;

        Console.WriteLine("Enter a Sentence");
        string sentence = Console.ReadLine().ToLower();
        char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

        total = sentence.Count(x => vowels.Contains(x));

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

        Console.ReadLine();
    }
like image 103
Tyler Avatar answered Sep 28 '22 23:09

Tyler


Right now, you're checking whether the sentence as a whole contains any vowels, once for each character. You need to instead check the individual characters.

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

That being said, you can simplify this quite a bit:

static void Main()
{
    int total = 0;
    // Build a list of vowels up front:
    var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };

    Console.WriteLine("Enter a Sentence");
    string sentence = Console.ReadLine().ToLower();

    for (int i = 0; i < sentence.Length; i++)
    {
        if (vowels.Contains(sentence[i]))
        {
            total++;
        }
    }
    Console.WriteLine("Your total number of vowels is: {0}", total);

    Console.ReadLine();
}

You can simplify it further if you want to use LINQ:

static void Main()
{
    // Build a list of vowels up front:
    var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };

    Console.WriteLine("Enter a 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();
}
like image 27
Reed Copsey Avatar answered Sep 28 '22 23:09

Reed Copsey


Since Reed has answered your question, I will offer you another way to implement this. You can eliminate your loop by using LINQ and lambda expressions:

string sentence = "The quick brown fox jumps over the lazy dog.";
int vowelCount = sentence.Count(c => "aeiou".Contains(Char.ToLower(c)));

If you don't understand this bit of code, I'd highly recommend looking up LINQ and Lambda Expressions in C#. There are many instances that you can make your code more concise by eliminating loops in this fashion.

In essence, this code is saying "count every character in the sentence that is contained within the string "aeiou". "

like image 31
fatsmcgee Avatar answered Sep 29 '22 00:09

fatsmcgee


That's because your if statement is always true, you need to compare the character at sentence[i], and see if it is a vowel, instead of seeing if the sentence contains a vowel.

like image 33
CBredlow Avatar answered Sep 29 '22 00:09

CBredlow


You were checking to see if your whole sentence contained vowels for every iteration of your loop, which is why your total was simply the number of characters in your sentence string.

foreach(char ch in sentence.ToLower())
    if("aeiou".Contains(ch))
        total++;

Better yet use a regular expression. edit You'd only want to use a regex for something a little more complex than matching vowels.

using System.Text.RegularExpressions;
...
int total = Regex.Matches(sentence, @"[AEIOUaeiou]").Count;

EDIT Just for completeness the fastest/most efficient (if you were to do this on a ~million strings) solution. If performance wasn't a concern I'd use Linq for its brevity.

public static HashSet<char> SVowels = new HashSet<char>{'a', 'e', 'i', 'o', 'u'};
public static int VowelsFor(string s) {
    int total = 0;
    foreach(char c in s)
        if(SVowels.Contains(c))
            total++;
    return total;
}
like image 34
Louis Ricci Avatar answered Sep 29 '22 01:09

Louis Ricci


There are many ways to skin a cat :-) In programming a little lateral thinking can be useful...

total += sentence.Length - sentence.Replace("a", "").Length;
total += sentence.Length - sentence.Replace("e", "").Length;
total += sentence.Length - sentence.Replace("i", "").Length;
total += sentence.Length - sentence.Replace("o", "").Length;
total += sentence.Length - sentence.Replace("u", "").Length;

You could, for example, try removing a vowel from the sentence and looking if the sentence is smaller without the vowel, and by how much.

like image 26
xanatos Avatar answered Sep 28 '22 23:09

xanatos


int cnt = 0;
for (char c in sentence.ToLower())
    if ("aeiou".Contains(c))
       cnt++;
return cnt;
like image 42
Curt Avatar answered Sep 28 '22 23:09

Curt