我如何计算字符串中的元音C#

时间:2015-02-02 11:55:02

标签: c# windows

我正在制作一个旨在计算单词中元音的程序,但是我无法计算每个单词的元音。我目前的代码如下:

    string word;
    string[] ca = { "a", "e", "i", "o", "u", "A", "E", "I", "O", "U" };
    int va = 0;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        if (ca.Contains(word))
        {

            label1.Text = "Vowel Count: " + va;
        }
        else
        {
            label1.Text = "Vowel Count: " + va;
        }
    }

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

最简单的方法是将字符串拆分为单词开头。这可以通过字符串Split()方法实现:

// you need to decide what the word separators are:
var words = text.Split(new char[]{'.', ',', ':', ';', '\r', '\t', '\n'});

一旦完成,它只是一个for循环:

foreach (var word in words)
{
    foreach (var character in word)
    {
        if (vowels.Any(x => x == character))
          ++count;
    }
}    

答案 1 :(得分:0)

你可以这样做:

string word = "myword";
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int vowelCount = word.Count(x => vowels.Contains(Char.ToLower(x)));