简体   繁体   中英

C# - How do I convert an uppercase letter to lowercase AND count it?

I am doing a school project and am required to count the number of letters, vowels, and consonants in a string from a textbox and display them in a labelbox. I understand there are easier ways to do this, but the instructions specify that I must use a switch statement to count the vowels. The code works well except that it counts uppercase vowels as consonants (and still includes them in letter total). Below is the code I created for my CountVowels method. Please note that this is the exact structure I am required to use. What am I missing?

private int CountVowels(string userInput)
{
    int vowels = 0;     //Total number of vowels

    //Count total number of vowels in string
    foreach (char ch in userInput)
    {
        if (!char.IsLetter(ch))
        {
            continue;
        }
        else if (char.IsUpper(ch))
        {
            char.ToLower(ch);
        }

        switch (ch)
        {
            case 'a':
                vowels++;
                break;

            case 'e':
                vowels++;
                break;

            case 'i':
                vowels++;
                break;

            case 'o':
                vowels++;
                break;

            case 'u':
                vowels++;
                break;
        }
    }
}

Your switch statement can be a bit simplified with ToLower() to the character. This is a working method.

private int CountVowels(string userInput)
{
    int vowels = 0;     //Total number of vowels
            
    //Count total number of vowels in string
    foreach (char ch in userInput)
    {    
        if (!char.IsLetter(ch))
        {
            continue;
        }

        switch (ch.ToLower())
        {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                vowels++;
                break;
        }
    }
    return vowels;
}

What it means is that if the letter is any vowel, it will increment vowels and move on to the next character. Make sure to add the return statement at the end to get the total number of vowels from this method.


Another way to go about it without changing your switch statement would be to lower the string in your foreach loop.

foreach (char ch in userInput.ToLower())

You can also create a new variable inside the foreach loop and use that in your switch statement.

foreach (char ch in userInput)
{    
    char lowerCh = ch;
    if (!char.IsLetter(ch))
    {
        continue;
    }
    else if (char.IsUpper(ch))
    {
        lowerCh = ch.ToLower();
    }

    switch(lowerCh)
    // *

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