从字符串中检索元音的方法

时间:2017-01-26 15:21:24

标签: c#

我需要通过名称“SelectOnlyVowels”创建一个方法,并从字符串“abc”中取出元音而不改变下面的代码。

const string abc = "asduqwezxc";  //this is the string
                foreach (var vowel in abc.SelectOnlyVowels())
                {
                    Console.WriteLine("{0}", vowel);
                }

2 个答案:

答案 0 :(得分:1)

看起来你正在寻找的是字符串扩展方法

https://msdn.microsoft.com/en-us//library/bb383977.aspx

这是一个有效的例子。

class Program
{
    static void Main(string[] args)
    {
        const string abc = "asduqwezxc";
        foreach (var vowel in abc.SelectOnlyVowels())
        {
            Console.WriteLine("{0}", vowel);
        }
        Console.ReadLine();
    }
}

public static class StringManipulation
{
    public static string SelectOnlyVowels(this string text)
    {
        var vowels = "aeiou";
        var result = "";
        foreach (char c in text)
        {
            if (vowels.Contains(c))
            {
                result += c;
            }
        }
        return result;
    }
}

答案 1 :(得分:0)

您只需要创建这样的扩展方法:

public static class StringExtensions
{
    public static string SelectOnlyVowels(this string text)
    {
        var vowels = "aeiou";
        return new String(text.Where(p => vowels.IndexOf(p.ToString(), StringComparison.InvariantCultureIgnoreCase) >= 0).ToArray());
    }
}