Sunday, February 14, 2016

How do I compare the alphabetic order of things in C#?

You can't compare strings, but you can compare characters like so:

[TestMethod]
public void compare_strings()
{
   char a = 'a';
   char b = 'b';
   Assert.IsTrue(a < b);
}

 
 

This test passes. a is less than b as it comes earlier in alphabetic order. Note that char types are declared in single ticks while a string is declared in double quotes. This test won't compile. This is the wrong way:

[TestMethod]
public void compare_strings()
{
   string a = "a";
   string b = "b";
   Assert.IsTrue(a < b);
}

 
 

Addendum 2/18/2016: It has been pointed out to me in the comments below that ASCII values are compared and thus there may be unexpected results when comparing a capital letter to a lowercase letter. To make my trick here work you will have to cast strings to lowercase before looping through their characters if you want a fair comparison.

No comments:

Post a Comment