【问题标题】:How do I count vowels in a string C# [duplicate]如何计算字符串C#中的元音[重复]
【发布时间】:2015-02-02 11:55:01
【问题描述】:

我正在开发一个旨在计算单词中元音的程序,但是我无法计算每个单词的元音。我当前的代码如下所示:

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

感谢您的帮助!

【问题讨论】:

  • 你现在写的检查单词是否存在于元音数组中,当然它不存在。

标签: c# windows


【解决方案1】:

最简单的方法是将字符串拆分为单词开头。这可以借助字符串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;
    }
}    

【讨论】:

    【解决方案2】:

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-02
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      相关资源
      最近更新 更多