C# 检查元音列表的字母顺序

C# 检查元音列表的字母顺序,c#,C#,我试图检查一个单词中的元音是否按字母顺序排列,如果不按字母顺序排列,则丢弃该单词。 我目前已经从单词中选择元音,并将它们添加到字符串中 foreach(char c in word[I]) { if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { vowelList.Add(c) } } 我如何检查此列表以确保它们是有序的,而不必将每个字符与其他每个字符进行比较 您可以使用LINQ

我试图检查一个单词中的元音是否按字母顺序排列,如果不按字母顺序排列,则丢弃该单词。 我目前已经从单词中选择元音,并将它们添加到字符串中

foreach(char c in word[I])
{
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
    {
        vowelList.Add(c)
    }
}
我如何检查此列表以确保它们是有序的,而不必将每个字符与其他每个字符进行比较

您可以使用LINQ,如:

bool IsOrdered = vowelList.OrderBy(c => c).SequenceEqual(vowelList);
如果使用
OrderBy
对字符进行排序,则列表
vowelList
将按照字符数组中的顺序包含字符

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

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

这应该有效地发挥作用:

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;
}
private static readonly char[]元音={'a','e','i','o','u'};
公共静态bool arewernalphabeticalorder(字符串字)
{
int lastIndex=-1;
for(int i=0;i=0)
{
if(元音索引
我可能会使用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);

您不需要将每个字符与每个字符进行比较。您只需要遍历字符串中的字符,将元音存储到temp,如果temp中已经存储了一个字符,则进行比较,查看新字符的值是否大于temp中的旧字符的值。O(n)溶液
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();