String.Compare()方法以及C#中的示例
C#方法String.Compare()
String.Compare()方法用于比较两个字符串对象,该方法基于第一个不同字符的差返回0,小于0或大于0的值。
语法:
int String.Compare(String1, String2);
参数:接受两个字符串进行比较。
返回值:返回一个int值-可以为0,小于0或大于0。
示例
Input:
string str1 = "nhooo";
string str2 = "nhooo";
Function call:
String.Compare(str1, str2)
Output:
0C#使用方法比较两个字符串的示例String.Compare()
using System;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//字符串变量
string str1 = "nhooo";
string str2 = "nhooo";
Console.WriteLine(String.Compare("ABCD", "ABCD"));
Console.WriteLine(String.Compare("ABCD", "abcd"));
Console.WriteLine(String.Compare("abcd", "ABCD"));
//检查条件
if (String.Compare(str1, str2)==0)
Console.WriteLine(str1 + " and " + str2 + " are same");
else
Console.WriteLine(str1 + " and " + str2 + " are not same");
str1 = "nhooo";
str2 = "nhooo";
if (String.Compare(str1, str2) == 0)
Console.WriteLine(str1 + " and " + str2 + " are same");
else
Console.WriteLine(str1 + " and " + str2 + " are not same");
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
0 1 -1 nhooo and nhooo are same nhooo and nhooo are not same
参考:String.Compare方法