C# Count Vowels

会有一股神秘感。 提交于 2019-11-27 21:36:50

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

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.

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

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

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

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.

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

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

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

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

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 ;
}
    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);
Fadi Alzoubi

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:

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

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;
        }
bilal
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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!