📜  C#| StringComparer.Compare方法

📅  最后修改于: 2021-05-29 23:00:09             🧑  作者: Mango

StringComparer.Compare方法用于比较两个对象或字符串,并返回其相对排序顺序的指示。此方法的重载列表中有2种方法:

  • 比较(对象,对象)
  • 比较(字符串,字符串)

比较(对象,对象)

此方法比较两个对象,并在派生类中重写时返回其相对排序顺序的指示。

句法:

public int Compare (object a, object b);

在此, a是要比较的第一对象, b是要比较的第二对象。

返回:此方法返回一个带符号的整数,该整数指示对象ab的相对值。根据下表返回值:

Value Meaning
Less than zero a precedes b in the sort order or a is null and b is not null.
Zero a is equal to b or a and b are both null.
Greater than zero a follows b in the sort order or b is null and a is not null.

异常:如果a和b都不是String对象,并且a和b都不实现IComparable接口,则此方法将提供ArgumentException。

例子:

// C# program to demonstrate the use of
// StringComparer.Compare(Object, Object)
// Method
using System;
using System.Collections;
  
class gfg {
  
    public class cmp : IComparer {
  
        // CaseInsensitiveComparer
        int IComparer.Compare(Object x, Object y)
        {
            return ((new CaseInsensitiveComparer()).Compare(x, y));
        }
    }
  
    // Main Method
    public static void Main()
    {
        // Initialize a string array.
        string[] arr = {"A", "E", "D", "C", "B"};
  
        // Display original array
        Console.WriteLine("Original array:");
        print(arr);
  
        // Sort the array using the default comparer.
        Array.Sort(arr);
        Console.WriteLine("Sort using sort function:");
        print(arr);
  
        // Sort the array using the comparer.
        Array.Sort(arr, new cmp());
        Console.WriteLine("Sorting using compare method :");
        print(arr);
    }
  
    // print function
    public static void print(IEnumerable list)
    {
        foreach(var v in list)
            Console.WriteLine(v);
  
        Console.WriteLine();
    }
}
输出:
Original array:
A
E
D
C
B

Sort using sort function:
A
B
C
D
E

Sorting using compare method :
A
B
C
D
E

比较(字符串,字符串)

此方法比较两个字符串,并在派生类中重写时返回其相对排序顺序的指示。

句法:

public abstract int Compare (string a, string b);

这里, a是要比较的第一字符串, b是要比较的第二字符串。

返回:此方法返回一个带符号的整数,该整数指示对象ab的相对值。根据下表返回值:

Value Meaning
Less than zero a precedes b in the sort order or a is null and b is not null.
Zero a is equal to b or a and b are both null.
Greater than zero a follows b in the sort order or b is null and a is not null.

异常:如果a和b都不是String对象,并且a和b都不实现IComparable接口,则此方法将提供ArgumentException。

例子:

// C# program to demonstrate the use of 
// StringComparer.Compare(String, String)
// Method
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        string s1 = "geek";
        string s2 = "Geek";
  
        int st = 0;
  
        // Compare(string, string) method
        st = string.Compare(s1, s2);
  
        Console.WriteLine(st.ToString());
    }
}
输出:
-1

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.stringcomparer.compare?view=netframework-4.8