- Home /
How do I find which string comes first alphabetically?
I have two stings and I need to be able to tell which one comes first so that I'll be able to go into an if statement. Here is some code that might show better what I am trying to do.
if(dataKey > "uqid"){
attributePos = 2;
}
// this returns an error because the > opterator cannot be
//used with a left hand side of type 'String' and a right
//hand side of type 'String'.
I know there must be some simple way of doing this, but I'm having a lot of trouble finding it. If anyone could help that would be great.
String.Compare might work if you just want to compare the two strings. But it looks like you are needing more functionality. Not only are you comparing them but you also want to know which one comes first if they were arranged alphabetically(at least that's what it sounds like). It looks like you'll have to make your own method that compares the strings and figures out which one is first if arranged alphabetically. If you are feeling adventurous you could probably write an overload for the > operator to do this. So, you could use it like how you have your example code. If not, it would probably look something like if(compareAlphabetically(string1, string2)){}
Answer by Dave-Carlile · Jan 23, 2013 at 07:05 PM
Don't know for sure if you're using C# or not, but String.Compare or String.CompareTo is what likely what you're looking for.