Reputation: 41
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
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
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
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