C# String Compare() Method
The Compare()
method in C# is a static method of the String
class that is used to compare two strings. It returns an integer that indicates the lexical relationship between the two strings.
The Compare()
method has several overloads that allow you to compare strings using different criteria. Here is an example of the basic overload:
string str1 = "apple"; string str2 = "banana"; int result = String.Compare(str1, str2); if (result < 0) { Console.WriteLine("{0} comes before {1} in the sort order", str1, str2); } else if (result > 0) { Console.WriteLine("{0} comes after {1} in the sort order", str1, str2); } else { Console.WriteLine("{0} and {1} are the same string", str1, str2); }Source:www.theitroad.com
In this example, we compare the two strings "apple" and "banana" using the Compare()
method. The Compare()
method returns a value that is less than 0 if str1
comes before str2
in the sort order, greater than 0 if str1
comes after str2
in the sort order, or 0 if the two strings are equal.
In this example, since "apple" comes before "banana" in the sort order, the Compare()
method returns a value less than 0, so we print a message indicating that "apple" comes before "banana" in the sort order.
The Compare()
method has overloads that allow you to perform case-insensitive comparisons, ignore white space, and compare substrings, among other things. Check the Microsoft documentation for more information about the Compare()
method and its overloads.