Compare()
方法按照字母顺序比较两个字符串。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str1 = "C#";
string str2 = "Programiz";
// compares str1 with str2
// returns -1 because C# comes before Programiz in alphabetical order
int result = String.Compare(str1, str2);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
// Output: -1
Compare() 语法
字符串 Compare()
方法的语法是
String.Compare(string str1, string str2)
这里,Compare()
是 String
类的一个方法。
Compare() 参数
Compare()
方法接受以下参数
- str1 - 用于比较的第一个字符串
- str2 - 用于比较的第二个字符串
Compare() 返回值
Compare()
方法返回
- 0 - 如果字符串相等
- 正整数 - 如果第一个字符串在字母顺序上排在第二个字符串之后
- 负整数 - 如果第一个字符串在字母顺序上排在第二个字符串之前
示例 1:C# String Compare()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str1 = "C#";
string str2 = "C#";
string str3 = "Programiz";
int result;
// compares str1 with str2
result = String.Compare(str1, str2);
Console.WriteLine(result);
//compares str1 with str3
result = String.Compare(str1, str3);
Console.WriteLine(result);
//compares str3 with str1
result = String.Compare(str3, str1);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
输出
0 -1 1
这里,
String.Compare(str1, str2)
返回 0,因为 str1 和 str2 相等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#";
// if str1 and str2 are equal, the result is 0
if(String.Compare(str1, str2) == 0) {
Console.WriteLine("str1 and str2 are equal");
}
else {
Console.WriteLine("str1 and str2 are not equal.");
}
Console.ReadLine();
}
}
}
输出
str1 and str2 are equal
由于 str1 等于 str2,String.Compare(str1, str2)
返回 0。
示例 3:C# String Compare() (区分大小写)
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str1 = "Programiz";
string str2 = "programiz";
int result;
// compares str1 and str2
result = String.Compare(str1, str2);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
输出
1
当将 "Programiz"
与 "programiz"
比较时,我们不会得到 0。这是因为 Compare()
方法会考虑字母的大小写。
示例 4:C# String Compare() - 忽略大小写
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str1 = "Programiz";
string str2 = "programiz";
int result;
bool ignoreCase = true;
// compares by ignoring case
result = String.Compare(str1, str2, ignoreCase);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
输出
0
当将 "Programiz"
与 "programiz"
比较时,我们得到 0。这是因为我们在方法参数中使用了 Boolean
值 true
,它在字符串比较时会忽略大小写。
注意事项:
Boolean
值false
在字符串比较时会考虑字母的大小写。- 我们可以在
String.Compare()
方法中使用其他参数,例如bool ignorecase
。