Roman Gusan
Roman Gusan

Reputation: 41

How to check if letters in a word are in alphabetical order?

There are a couple of words in English language that consist of letters, which are in alphabetical order, namely: hot, fry, fuzz, am, in, hoops and almost.

I need a method that checks if letters in a word satisfy above specifications.

All I could think of is to create an alphabet array, and test if each consecutive letter has a higher index in the alphabet array.

Upvotes: 1

Views: 3635

Answers (3)

I4V
I4V

Reputation: 35353

string s = "hoops";
bool inOrder = s == String.Join("", s.OrderBy(c => c));

or

bool inOrder = s.SequenceEqual(s.OrderBy(c => c));

Upvotes: 17

VladL
VladL

Reputation: 13043

You can use this simple non-linq function, in case you have to use .net 2.0 like me for example :)

  private bool isAlphabetic(string toCheck)
  {
     toCheck = toCheck.ToLower();
     for (int i = 0; i < toCheck.Length; i++)
     {
        if (i+1 < toCheck.Length && toCheck[i] > toCheck[i + 1])
           return false;
     }

     return true;
  }

Upvotes: 0

tumtumtum
tumtumtum

Reputation: 1162

The other answers create temporary strings and also run through all letters unnecessarily. Try this :) (I'm assuming case sensitivity doesn't matter).

bool LettersAreInAlphabeticalOrder(string word)
{
    for (int i = 1; i < word.Length; i++)
    {
        if (Char.ToLower(word[i]) < Char.ToLower(word[i - 1]))
        {
            return false;
        }
    }

    return true;
}

Upvotes: 5

Related Questions