在 C# 中按字典顺序比较两个字符串
csharpserver side programmingprogramming更新于 2025/9/23 18:53:00
要在 C# 中比较字符串,请使用 compare() 方法。它比较两个字符串并返回以下整数值 −
如果 str1 小于 str2,则返回 -1。 如果 str1 等于 str2,则返回 0。 如果 str1 大于 str2,则返回 1。
在 String.compare() 方法中设置两个字符串并比较它们 −
string.Compare(string1, string2);
示例
您可以尝试运行以下代码来在 C# 中比较两个字符串。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
string string1 = null;
string string2 = null;
string1 = "amit";
string2 = "Amit";
int myOutput = 0;
myOutput = string.Compare(string1, string2);
Console.WriteLine(myOutput.ToString());
Console.ReadLine();
}
}
}
输出
-1

