📅  最后修改于: 2023-12-03 15:00:14.932000             🧑  作者: Mango
StringComparer.Compare
method is a method in the System.StringComparer
class in C#. It is used to compare two strings based on the specified comparison rules.
public abstract int Compare(string x, string y)
x : The first string to compare.
y : The second string to compare.
The Compare
method returns an integer that indicates the lexical relationship between the two strings being compared.
The return value is:
x
is less than y
.x
is equal to y
.x
is greater than y
.// Create an instance of the StringComparer class
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
// Compare two strings using the Compare method
int result1 = comparer.Compare("dog", "DOG");
int result2 = comparer.Compare("cat", "dog");
int result3 = comparer.Compare("horse", "HORSE");
// Display the results
Console.WriteLine(result1); // 0
Console.WriteLine(result2); // -1
Console.WriteLine(result3); // 0
In this example, we create an instance of the StringComparer
class using the OrdinalIgnoreCase
parameter, which specifies that the comparison should be case-insensitive.
We then use the Compare
method to compare the strings "dog" and "DOG", "cat" and "dog", and "horse" and "HORSE". The results are 0, -1, and 0 respectively.
StringComparer.Compare
method is a useful method to compare two strings based on the specified comparison rules. It is important to note that the Compare
method is case-sensitive by default. However, you can use the StringComparer
class to create an instance of the comparer with specific rules, such as case-insensitive.