Phorden
Phorden

Reputation: 1034

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();
    }

Upvotes: 10

Views: 65514

Answers (20)

jeetjeet
jeetjeet

Reputation: 11

Here was how I did it:

char[] englishWord = new Char[5] { 'a', 'e', 'i', 'o', 'u' };

string input = Console.ReadLine();

input.ToLower();

int count = 0;

for (int i = 0; i < input.Length; i++)
{
    for (int j = 0; j < englishWord.Length; j++)
    {
        if (input[i] == englishWord[j])
        {
            count++;
            break;
        }
    }
}

Console.WriteLine(count);

Upvotes: 0

belal ahmad
belal ahmad

Reputation: 69

`public static void Main()
{
    Console.WriteLine("Enter a Sentence");
    string sentence = Console.ReadLine().ToLower();

    string voval="aeiou";
    int cnt=0;
    foreach(char ch in sentence)
    {
        if(voval.Contains(ch.ToString()))
        {
            cnt++;
        }
    }
    Console.WriteLine(cnt); 
}`

Upvotes: 0

Miroslav Atanasov
Miroslav Atanasov

Reputation: 1

We check each subsequent letter of the expression if it is equal to the vowels in the array

class Program
{

    private static void Main(string[] args)
    {
        string random = Console.ReadLine();
        string toLower = random.ToLower();
        char []isVowels = { 'a','e','i','o','u','y' };
        byte count = 0;
        for (int i = 0; i < toLower.Length; i++)
        {
            for (int j = 0; j < isVowels.Length; j++)
            {
                if (toLower[i]==isVowels[j])
                {
                    count++;
                }
            }
        }
        Console.WriteLine(count);
    }
    

}

Upvotes: 0

Mapachu
Mapachu

Reputation: 1

// Using two loops.

        char[] vowels= new char[]{'a', 'e', 'i', 'o', 'u',
                                   'A', 'E', 'I', 'O', 'U'}; 
        string myWord= "This is a beautiful word.";
        
        int numVowels = 0;
        
        foreach(char c in  myWord.ToCharArray())
        {
            foreach(char c2 in vowels)
            {
                if(c == c2) numVowels++;    
            }  
        }
        
        Console.WriteLine($"{numVowels} vowels in: {myWord}");

Upvotes: 0

Rishu Ranjan
Rishu Ranjan

Reputation: 574

We can use regular expression to match vowels in a sentence.

Regex.Matches() function will return an array with all occurrence of vowel. Then we can use the count property to find the count of vowels.

Regular expression to match vowels in a string: [aeiouAEIOU]+

Below is the working code snippet:

 public static void Main()
   {
       string pattern = @"[aeiouAEIOU]+";
       Regex rgx = new Regex(pattern);
       string sentence = "Who writes these notes?";
       Console.WriteLine(rgx.Matches(sentence).Count);
   }

Upvotes: 0

Fadi Alzoubi
Fadi Alzoubi

Reputation: 1

Application to count vowels and consonants letters in a sentence. This is another solution with less lines of code with understanding the idea of using loops and nested loops with char arrays.

An application interface with control names:

Application interface with controls names

namespace Program8_4
{
  public partial class Form1 : Form
  {
    // declare the counter variables in field
    int iNumberOfVowels = 0;
    int iNumberOfConsonants = 0;
    public Form1()
    {
        InitializeComponent();
    }

    private void btnFind_Click(object sender, EventArgs e)
    {
        // call the methods in this event
        GetVowels(txtStringInput.Text);
        GetConsonants(txtStringInput.Text);
        // show the result in a label
        lblOutput.Text = "The number of vowels : " + iNumberOfVowels.ToString()+ Environment.NewLine+
            "The number of consonants : " + iNumberOfConsonants.ToString();
        // assign zero the counters to not add the previous number to new number, and start counting from zero again
        iNumberOfVowels = 0;
        iNumberOfConsonants = 0;

    }

    private int GetConsonants(string strFindConsonants)
    {
        // Declare char array to contain consonants letters
        char[] chrConsonants = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'X',
            'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x' };

        // loop to get each letter from sentence
        foreach (char Consonants in strFindConsonants)
        {
        // another nested loop to compare each letter with all letters contains in chrConsonants array
            for (int index= 0; index<chrConsonants.Length;index++)
            {
                // compare each letter with each element in charConsonants array
                if (Consonants == chrConsonants[index])

                {
                    // If it is true add one to the counter iNumberOfConsonants
                    iNumberOfConsonants++;
              }

            }
        }
        // return the value of iNumberOfConsonants
        return iNumberOfConsonants;
    }

    private int GetVowels(string strFindVowels)

    {
        // Declare char array to contain vowels letters
        char[] chrVowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O','U' };

        // loop to get each letter from sentence
        foreach (char Vowels in strFindVowels)
        {
            // another nested loop to compare each letter with all letters contains in chrVowels array
            for (int index = 0; index< chrVowels.Length; index++)
            {
                // compare each letter with each element in chrVowels array
                if (Vowels == chrVowels[index])

            {
                    // If it is true add one to the counter iNumberOfVowels
                    iNumberOfVowels = iNumberOfVowels+1;

            }
            }
        }
        // return the value of iNumberOfVowels
        return iNumberOfVowels;
    }

Upvotes: 0

Jacob Hernandez
Jacob Hernandez

Reputation: 1

    static void Main(string[] args)
    {
        Char[] ch;
        Console.WriteLine("Create a sentence");
        String letters = Console.ReadLine().Replace(" ", "").ToUpper();
        ch = letters.ToCharArray();
        int vowelCounter = 0;
        int consonantCounter = 0;

       for(int x = 0; x < letters.Length; x++)
        {
            if(ch[x].ToString().Equals("A") || ch[x].ToString().Equals("E") || ch[x].ToString().Equals("I") || ch[x].ToString().Equals("O") || ch[x].ToString().Equals("U"))
            {
                vowelCounter++;
            }
            else
            {
                consonantCounter ++;
            }
        }
        System.Console.WriteLine("Vowels counted : " + vowelCounter);
        System.Console.WriteLine("Consonants counted : " + consonantCounter);

Upvotes: 0

bilal
bilal

Reputation: 1

void main()
{
    int x=0;
    char ch;
    printf("enter a statement:");
    while((ch=getche())='\r')
    {
        if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
        x++;
    }
    printf("total vowels=");
    getch();
}

Upvotes: -1

castaway2000
castaway2000

Reputation: 324

this is a nice generic way to count vowels and from here you can do all sorts of things. count the vowels, return a sorted list, etc.

public static int VowelCount(String vowelName) {
            int counter = 0;
            char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
            for (int index = 0; index < vowelName.Length; index++)
            {
                if (vowels.Contains(vowelName[index])) 
                {
                    counter++;
                }
            }
            return counter;
        }

Upvotes: -1

Curt
Curt

Reputation: 5722

int cnt = 0;
for (char c in sentence.ToLower())
    if ("aeiou".Contains(c))
       cnt++;
return cnt;

Upvotes: 1

Louis Ricci
Louis Ricci

Reputation: 21106

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;
}

Upvotes: 2

Nicholas Carey
Nicholas Carey

Reputation: 74307

TMTOWTDI (Tim Toadie as they say: There's More Than One Way To Do It).

How about

static char[] vowels = "AEIOUaeiou".ToCharArray() ;
public int VowelsInString( string s  )
{

  int n = 0 ;
  for ( int i = 0 ; (i=s.IndexOfAny(vowels,i)) >= 0 ; )
  {
    ++n ;
  }

  return n;
}

Or (another regular expression approach)

static readonly Regex rxVowels = new Regex( @"[^AEIOU]+" , RegexOptions.IgnoreCase ) ;
public int VowelCount( string s )
{
  int n = rxVowels.Replace(s,"").Length ;
  return n ;
}

The most straightforward is probably the fastest, as well:

public int VowelCount( string s )
{
  int n = 0 ;
  for ( int i = 0 ; i < s.Length ; +i )
  {
    switch( s[i] )
    {
    case 'A' : case 'a' :
    case 'E' : case 'e' :
    case 'I' : case 'i' :
    case 'O' : case 'o' :
    case 'U' : case 'u' :
      ++n ;
      break ;
    }
  }
  return n ;
}

Upvotes: 0

Chris
Chris

Reputation: 701

You can also do this with switch statement

        var total = 0;
        var sentence = "Hello, I'm Chris";
        foreach (char c in sentence.ToLower())
        {
            switch (c)
            {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                    total++;
                    break;
                default: continue;
            }

        }
        Console.WriteLine(total.ToString());

Upvotes: 0

fatsmcgee
fatsmcgee

Reputation: 314

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". "

Upvotes: 7

xanatos
xanatos

Reputation: 111890

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.

Upvotes: 0

Antarr Byrd
Antarr Byrd

Reputation: 26131

This is how I would handle this.

var sentence = "Hello my good friend";
            var sb = sentence.ToLower().ToCharArray();
            var count = 0;
            foreach (var character in sb)
            {
                if (character.Equals('a') || character.Equals('e') || character.Equals('i') || character.Equals('o') ||
                    character.Equals('u'))
                {
                    count++;
                }
            }

Upvotes: 0

Fede
Fede

Reputation: 44048

Maybe too advanced for a starter, but this is the way you do that in C#:

var vowels = new[] {'a','e','i','o','u'};

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

var vowelcount = sentence.Count(x => vowels.Contains(x));

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

Upvotes: 0

Tyler
Tyler

Reputation: 578

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();
    }

Upvotes: 2

CBredlow
CBredlow

Reputation: 2840

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.

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564631

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();
}

Upvotes: 32

Related Questions