#96 – Comparing String Values

The < and > operators are not overloaded for the System.String type, which means that you can’t compare strings using the relational operators.

Instead. you can use the static System.String.Compare method, which takes two strings and returns an integer value.  If the first string is less than the second, a negative number is returned.  If the first string is greater, a positive number is returned.  If the strings are equal, the return value is zero.

 int n = string.Compare("Sean", "Steinbeck");    // -1
 n = string.Compare("Sean", "Bozo");             // 1
 n = string.Compare("Sean", "Sean");             // 0
 n = string.Compare("Sean", "sean");             // 1 ("S" > "s")

You can also use the CompareTo instance method of the string type:

 int n = "Sean".CompareTo("Giotto");   // 1 (Sean > Giotto)

You can also ignore case during the comparison:

 n = string.Compare("Sean", "sean", true);         // 0
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: