Why my program does not read subsuquent letters after index 0?

Viewed 61

I am trying to code in C# and ran into this problem that says I need to count how many vowel/s there is/are in the entered string. It only identifies the first letter. Here is the program:

class CountVowelsModularized
{
    public static void Main()
    {
        // Write your main here.
        string word;

        WriteLine("Enter a word");
        word=ReadLine().ToUpper();

        WriteLine("This word has {0} vowels", CountVowels(word));
    }

    public static int CountVowels(string phrase)
    {
        // Write your CounVowels method here.
        int vowel_count=0;
        int i=0;
        for(i=0;i<phrase.Length;i++)
        {
            if(phrase[i]=='A'||phrase[i]=='E'||phrase[i]=='I'||phrase[i]=='O'||phrase[i]=='U')
            {
                vowel_count++;
                ++;
            }
            else
                i++;
        }

        return vowel_count;
    }
}
2 Answers

There are certainly more than a few ways to solve this requirement, but I am a fan of Regular Expressions. As an alternative method let me suggest:

    private static int CountVowels(string phrase)
    {
        var reg = new Regex(@"[AEIOU]",RegexOptions.IgnoreCase);
        return reg.Matches(phrase).Count();
    }

Regular Expressions are extremely powerful and well worth learning the basics.


EDIT

But keeping with your original code, this would suffice:

public static int CountVowels(string phrase)
{
    // Write your CounVowels method here.
    int vowel_count = 0;
    for (int i = 0; i < phrase.Length; i++)
    {
        if (phrase[i] == 'A' || phrase[i] == 'E' || phrase[i] == 'I' || phrase[i] == 'O' || phrase[i] == 'U')
        {
            vowel_count++;
        }
    }

    return vowel_count;
}

Your code works fine if you delete out the lines I have commented out:

public static int CountVowels(string phrase)
{
    // Write your CounVowels method here.
    int vowel_count = 0;
    int i = 0;
    for (i = 0; i < phrase.Length; i++)
    {
        if (phrase[i] == 'A' || phrase[i] == 'E' || phrase[i] == 'I' || phrase[i] == 'O' || phrase[i] == 'U')
        {
            vowel_count++;
            // ++; - DELETE THIS
        }
        // else - DELETE THIS
            // i++; - DELETE THIS
    }

    return vowel_count;
}

If you'd like to make your code a little more concise here is a simple refactoring:

public static int CountVowels(string phrase)
{
    // Write your CounVowels method here.
    int vowel_count = 0;
    for (int i = 0; i < phrase.Length; i++)
    {
        if ("AEIOU".Contains(phrase[i]))
        {
            vowel_count++;
        }
    }
    return vowel_count;
}

If you'd like to go for a more radical refactor then try this:

public static int CountVowels(string phrase) => phrase.Where(p => "AEIOU".Contains(p)).Count();
Related