C# `String.CompareTo()`: Performing Lexicographical String Comparisons
Learn how to use C#'s `String.CompareTo()` method for comparing strings and determining their lexicographical order. This tutorial explains its functionality, different overloads, return values, and demonstrates its usage in various string comparison and sorting scenarios.
Understanding C#'s `CompareTo()` Method for Strings
The C# `CompareTo()` method compares a string instance with another string, determining their relative order based on lexicographical sorting. It's a fundamental method for string manipulation and comparison.
`CompareTo()` Method Signatures
The `CompareTo()` method has two versions:
public int CompareTo(string str)
: Compares the current string instance with the specified string (`str`).public int CompareTo(object obj)
: Compares the current string instance with another object. The object must be a string; otherwise, it will throw an exception.
Parameters
The first version takes a string as a parameter. The second version takes an object that must be a string; otherwise, an exception is thrown.
Return Value
The method returns an integer:
- 0: The two strings are equal.
- Positive Number: The current string instance comes *after* the specified string in lexicographical order.
- Negative Number: The current string instance comes *before* the specified string in lexicographical order.
Example
using System;
public class StringExample {
public static void Main(string[] args) {
string str1 = "apple";
string str2 = "apple";
string str3 = "banana";
Console.WriteLine(str1.CompareTo(str2)); // Output: 0
Console.WriteLine(str1.CompareTo(str3)); // Output: -1
}
}
This example demonstrates comparing two strings using `CompareTo()`. The output shows that "apple" is equal to "apple" (0), and "apple" comes before "banana" (-1).