String order comparison
String’s CompareTo instance method performs culture-sensitive, case-sensitive order
comparison. Unlike the == operator, CompareTo does not use ordinal comparison: for
ordering, a culture-sensitive algorithm is much more useful.
Here’s the method’s definition:
public int CompareTo (string strB);
The CompareTo instance method implements the generic
IComparable interface, a standard comparison protocol used
across the .NET Framework. This means string’s CompareTo
defines the default ordering behavior strings, in such applica-
tions as sorted collections, for instance. For more information
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);
The last two methods are simply shortcuts for calling the first two methods.
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:
Console.WriteLine ("Boston".CompareTo ("Austin")); // 1
Console.WriteLine ("Boston".CompareTo ("Boston")); // 0
Console.WriteLine ("Boston".CompareTo ("Chicago")); // -1
Console.WriteLine ("?".CompareTo ("u")); // 0
Console.WriteLine ("foo".CompareTo ("FOO")); // -1
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);
No comments:
Post a Comment