检查元音列表的字母顺序

时间:2015-03-25 15:51:45

标签: c#

我正在尝试检查一个单词中的元音是否按字母顺序排列,如果不是丢弃该单词。 我现在已经选择了单词中的元音并将它们添加到字符串中;

foreach(char c in word[I])
{
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
    {
        vowelList.Add(c)
    }
}

如何查看此列表以确保它们按顺序排列而不必将每个字符与其他每个字符进行比较?

3 个答案:

答案 0 :(得分:2)

您可以使用LINQ,如:

bool IsOrdered = vowelList.OrderBy(c => c).SequenceEqual(vowelList);

您的列表vowelList将包含字符数组中的字符,如果您使用OrderBy对其进行排序,则应与原始列表相同。

除此之外,您还可以将支票修改为:

if (new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(c))

答案 1 :(得分:0)

这应该有效:

private static readonly char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
public static bool AreVowelsInAlphabeticalOrder(string word)
{
    int lastIndex = -1;
    for (int i = 0; i < word.Length; i++)
    { 
        char c = word[i];
        int vowelIndex = Array.IndexOf(vowels, c);
        if(vowelIndex >= 0)
        {
            if(vowelIndex < lastIndex)
                return false;
            else
                lastIndex = vowelIndex;
        }
    }
    return true;
}

答案 2 :(得分:0)

我可能会使用LINQ做这样的事情:

// This list is to keep track of which letters are vowels
var vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' };

// This is the word we want to check the order of
string word = "testing"; // gives true

// We start of by finding all vowels in the word (in the order they appear)
var vowelList = word.Where(letter => vowels.Any(v => letter == v));

// We create a list that looks like we expect it to if its correct order
var expectedResult = vowelList.OrderBy(x => x);

// We check if we have a result in the expected order
bool isOrdered = vowelList.SequenceEqual(expectedResult);

这可以作为字符串的扩展方法实现,如下所示:

public static class StringExtensions
{
    static readonly List<char> _vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' };

    public static bool VowelsOrdered(this string word)
    {
        var vowelList = word.Where(letter => _vowels.Any(v => letter == v));
        var expectedResult = vowelList.OrderBy(x => x);

        return vowelList.SequenceEqual(expectedResult);
    }

    // Could also be implemented with a lower complexity like this
    public static bool VowelsOrdered2(this string word)
    {
        char last = _vowels[0];
        foreach (var c in word)
        {
            if (_vowels.Any(x => x == c))
            {
                if (c < last)
                    return false;
                else
                    last = c;
            }
        }
        return true;
    }
}

然后使用就像:

string word = "testing";
bool isOrdered = word.VowelsOrdered();