跳到主要内容

C# String Compare() 字符串比较方法

Compare() 方法按字母顺序比较两个字符串。

示例

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str1 = "C#";
string str2 = "Programiz";

// 比较 str1 和 str2
// 返回 -1 因为在字母顺序中 C# 出现在 Programiz 之前
int result = String.Compare(str1, str2);
Console.WriteLine(result);

Console.ReadLine();
}
}
}

// 输出:-1

Compare() 语法

字符串 Compare() 方法的语法是:

String.Compare(string str1, string str2)

这里,Compare()String 类的一个方法。

Compare() 参数

Compare() 方法接受以下参数:

  • str1 - 用于比较的第一个字符串
  • str2 - 用于比较的第二个字符串

Compare() 返回值

Compare() 方法返回:

  • 0 - 如果字符串相等
  • 正整数 - 如果第一个字符串在字母顺序中位于第二个字符串之后
  • 负整数 - 如果第一个字符串在字母顺序中位于第二个字符串之前

示例 1:C# 字符串比较 Compare()

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str1 = "C#";
string str2 = "C#";
string str3 = "Programiz";

int result;

// 比较 str1 和 str2
result = String.Compare(str1, str2);
Console.WriteLine(result);

// 比较 str1 和 str3
result = String.Compare(str1, str3);
Console.WriteLine(result);

// 比较 str3 和 str1
result = String.Compare(str3, str1);
Console.WriteLine(result);

Console.ReadLine();
}
}
}

输出

0
-1
1

这里,

  • String.Compare(str1, str2) 返回 0 因为 str1str2 相等
  • String.Compare(str1, str3) 返回 -1 因为 str1 出现在 str3 之前
  • String.Compare(str3, str1) 返回 1 因为 str3 出现在 str1 之后

示例 2:检查两个字符串是否相等

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str1 = "C#";
string str2 = "C#";

// 如果 str1 和 str2 相等,则结果为 0
if(String.Compare(str1, str2) == 0) {

Console.WriteLine("str1 和 str2 相等");
}

else {
Console.WriteLine("str1 和 str2 不相等。");
}

Console.ReadLine();
}
}
}

输出

str1 和 str2 相等

由于 str1 等于 str2String.Compare(str1, str2) 返回 0

示例 3:C# 字符串 Compare() 方法区分大小写

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str1 = "Programiz";
string str2 = "mashangxue123";

int result;

// 比较 str1 和 str2
result = String.Compare(str1, str2);
Console.WriteLine(result);

Console.ReadLine();
}
}
}

输出

1

"Programiz""mashangxue123" 比较时,结果不是 0。这是因为 Compare() 方法考虑了字母大小写。

示例 4:C# 字符串 Compare() 方法 - 忽略大小写

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str1 = "Programiz";
string str2 = "mashangxue123";

int result;
bool ignoreCase = true;

// 忽略大小写进行比较
result = String.Compare(str1, str2, ignoreCase);
Console.WriteLine(result);

Console.ReadLine();
}
}
}

输出

0

"Programiz""mashangxue123" 比较时,结果为 0。这是因为我们在方法参数中使用了 Booleantrue,它在字符串比较时忽略了大小写。

注意

  • Booleanfalse 在字符串比较时会考虑字母大小写。
  • 我们可以在 String.Compare() 方法中添加额外的参数,比如 bool ignorecase