HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Checking if a string contains vowels

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkingstringcontainsvowels

Problem

I'm just learning C# and wrote a little program to check if a word contains vowels. It's fairly simple and not to exciting but I would like to know if there's easier ways to do this:

using System;

namespace check_vowels
{
    class Program
    {
        static void Main(string[] args)
        {
            string word;

            Console.WriteLine("We will check if your string contains any vowels or not.");
            Console.Write("Enter a word: ");
            word = Console.ReadLine();
            if (word.ToLower().Contains("a") || (word.ToLower().Contains("e")))
            {
                Console.WriteLine("Your word contains the vowel 'A' or the Vowel 'E', or both.");
            }
            else if ((word.ToLower().Contains("i")) || (word.ToLower().Contains("o")))
            {
                Console.WriteLine("Your word contains the vowel 'I', or 'O', or both.");
            }
            else if (word.ToLower().Contains("u"))
            {
                Console.WriteLine("Your word contains the vowel 'U'.");
            }
            else
            {
                Console.WriteLine("Your word contains no vowels.");
            }

            Console.ReadLine();
        }
    }
}


What can I do better? What did I do well? How can I shorten this?

Solution

You could potentially do:

var vowels = Console.ReadLine()
     .Where(c => "aeiouAEIOU".Contains(c))
     .Distinct();

foreach(var vowel in vowels)
     Console.WriteLine("Your phrase contains a vowel of {0}", vowel);

if(!vowels.Any())
    Console.WriteLine("No vowels have been detected.");


So you understand the code a bit:

  • Where() : Will test each character to see if it is indeed a vowel or not.



  • Distinct() : Will remove duplicate vowels found.



Then you loop through the vowels stating what exist inside, then the if will simply return when loop is empty.

Code Snippets

var vowels = Console.ReadLine()
     .Where(c => "aeiouAEIOU".Contains(c))
     .Distinct();

foreach(var vowel in vowels)
     Console.WriteLine("Your phrase contains a vowel of {0}", vowel);

if(!vowels.Any())
    Console.WriteLine("No vowels have been detected.");

Context

StackExchange Code Review Q#128767, answer score: 14

Revisions (0)

No revisions yet.