string.Compare
是 C# 中用于比较两个字符串的方法。它返回一个整数,表示两个字符串在字典顺序(lexicographical order)中的相对关系。这个方法非常有用,尤其是在排序、查找或比较字符串时。
string.Compare
的详细说明
方法签名
public static int Compare(string strA, string strB);
参数
strA
:要比较的第一个字符串。strB
:要比较的第二个字符串。
返回值
- 小于 0:
strA
在字典顺序中位于strB
之前。 - 等于 0:
strA
和strB
相等。 - 大于 0:
strA
在字典顺序中位于strB
之后。
字典顺序(Lexicographical Order)
字典顺序是基于字符的 Unicode 值进行比较的。例如:
- 小写字母
a
的 Unicode 值是 97,大写字母A
的 Unicode 值是 65。 - 数字
0
的 Unicode 值是 48,数字9
的 Unicode 值是 57。
因此,字符串的比较是基于每个字符的 Unicode 值逐个进行的。
示例代码
以下是一些使用 string.Compare
的示例:
示例 1:基本比较
using System;
class Program
{
static void Main()
{
string str1 = "apple";
string str2 = "banana";
int result = string.Compare(str1, str2);
if (result < 0)
{
Console.WriteLine($"{
str1} 在 {
str2} 之前");
}
else if (result == 0)
{
Console.WriteLine(