我如何使用IndexOf和Substring列出句子中以元音开头的单词。 (C#)

问题描述 投票:0回答:1

我尝试使用不同的方法来打印给定句子中的元音。我无法弄清楚。

c# windows visual-studio substring indexof
1个回答
0
投票

元音字母为u,e,o,a,i,只需将句子拆分为单词并将其循环以进行检查,无需使用subtring或indexof

    public static void MainFunc()
    {
        string sentence = "An ugly cat sleeps in the sofa";

        Console.WriteLine(string.Join(';', ShowVowelWords(sentence)));
    }

    static char[] VOWELS = new char[] { 'u', 'e', 'o', 'a', 'i' };

    public static IEnumerable<string> ShowVowelWords(string sentence)
    {
        foreach (var word in sentence.ToLower().Split(' '))
            foreach (var c in VOWELS)
                if (word.StartsWith(c))
                    yield return word;
    }

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.