CSharp - String order comparison


String's CompareTo instance method performs culture-sensitive, case-sensitive order comparison.

Here's the method's definition:

public int CompareTo (string strB);

For other kinds of comparison, you can call the static Compare and CompareOrdinal methods:

public static int Compare (string strA, 
                           string strB,
                           StringComparison comparisonType);

public static int Compare (string strA, 
                           string strB, 
                           bool ignoreCase,
                           CultureInfo culture);

public static int Compare (string strA, 
                           string strB, 
                           bool ignoreCase);

public static int CompareOrdinal (string strA, 
                                  string strB);

All of the order comparison methods return a positive number, a negative number, or zero, depending on whether the first value comes after, before, or alongside the second value:


using System;
class MainClass/*from   w ww  . jav  a  2  s .  c o m*/
   public static void Main(string[] args)
     Console.WriteLine ("B".CompareTo ("A"));    
     Console.WriteLine ("B".CompareTo ("B"));    
     Console.WriteLine ("B".CompareTo ("C"));   
     Console.WriteLine ("foo".CompareTo ("FOO"));          



The following performs a case-insensitive comparison using the current culture:

Console.WriteLine (string.Compare ("foo", "FOO", true));   // 0

By supplying a CultureInfo object, you can plug in any alphabet:
// CultureInfo is defined in the System.Globalization namespace

CultureInfo german = CultureInfo.GetCultureInfo ("de-DE");
int i = string.Compare ("M?ller", "Muller", false, german);