C# 字符串 - Compare() 方法

C# 字符串 Compare() 方法用于返回一个整数,该整数表示两个指定字符串对象按指定规则排序后的相对位置。

以下整数表示相对位置 -

  • 小于零:按排序顺序,第一个子字符串位于第二个子字符串之前。
  • 零:子字符串按排序顺序出现在相同位置,或长度为零。
  • 大于零:按排序顺序,第一个子字符串位于第二个子字符串之后。

语法

以下是 C# 字符串 Compare() 方法的语法 -

public static int Compare (string? strA, string? strB, StringComparison comparisonType);

参数

此方法接受以下参数 -

  • strA:要比较的第一个字符串。
  • strB:要比较的第二个字符串。
  • comparisonType:指定比较规则的枚举值之一。

返回值

此方法返回一个整数,指示两个字符串之间的词汇关系。

示例 1:基本比较

这是字符串 Compare() 方法的基本示例。在这里,我们使用默认的比较语法:Compare(string? strA, string? strB)

    
using System;
class Program {
   static void Main() {
      string str1 = "tutorialspoint";
      string str2 = "tutorialsPoint_India";

      int result = String.Compare(str1, str2);

      if (result < 0)
         Console.WriteLine($"{str1} comes before {str2}");
      else if (result > 0)
         Console.WriteLine($"{str1} comes after {str2}");
      else
         Console.WriteLine($"{str1} is equal to {str2}");
   }
}

输出

以下是输出 -

tutorialspoint comes before tutorialsPoint_India

示例 2:不区分大小写的比较

让我们看另一个 Compare() 方法的示例。这里,我们使用了另一种比较语法,即 Compare(string? strA, string? strB, bool ignoreCase)

using System;
class Program {
   static void Main() {
      string str1 = "TutorialsPoint";
      string str2 = "tutorialspoint";
      
      // 忽略大小写 true
      int result = String.Compare(str1, str2, true);
   
      Console.WriteLine(result == 0 ? "Strings are equal" : "Strings are not equal");
   }
}

输出

以下是输出 -

Strings are equal

示例 3:特定于文化的比较

让我们看看字符串 Compare() 方法的另一种语法,这里我们将使用特定于文化的比较语法:Compare(string? strA, string? strB, StringComparison compareType)

using System;
class Program {
   static void Main() {
      string str1 = "strae";
      string str2 = "strasse";

      // 特定文化比较
      int result = String.Compare(str1, str2, StringComparison.CurrentCulture);
      
      if(result == 0 ){
         Console.WriteLine("Strings are equal in culture-specific comparison");
      }
      else{
         Console.WriteLine("Strings are not equal");
      }
   }
}

输出

以下是输出 -

Strings are equal in culture-specific comparison

示例 4:子字符串比较

以下示例使用 Compare() 方法,这里我们将使用子字符串比较语法:Compare(string? strA, int indexA, string? strB, int indexB, int length)

using System;
class Program {
   static void Main() {
      string str1 = "abcdef";
      string str2 = "abcxyz";
      
      // 比较前 3 个字符
      int result = String.Compare(str1, 0, str2, 0, 3); 

      Console.WriteLine(result == 0 ? "Substrings are equal" : "Substrings are not equal");
   }
}

输出

以下是输出 -

Substrings are equal

csharp_strings.html