一、使用等号
String a1 = "hello";
string a2 = "hello";
Console.WriteLine(a1 + a2);
if (a1 == a2)
{
Console.WriteLine("两个字符串相等");
}
else
{
Console.WriteLine("两个字符串不相等");
}
判断结果
Hello, World!
hellohello
两个字符串相等
二、使用equals来比较
String a1 = "hello1";
string a2 = "hello2";
Console.WriteLine(a1 + a2);
if (a1.Equals(a2))
{
Console.WriteLine("两个字符串相等");
}
else
{
Console.WriteLine("两个字符串不相等");
}
判断结果
Hello, World!
hello1hello2
两个字符串不相等
三、使用string.Compare()来比较
String a1 = "hello3";
string a2 = "hello2";
Console.WriteLine(a1 + a2);
int result = string.Compare(a1, a2);
if (result == 0)
{
Console.WriteLine("两个字符串相等");
}
else if (result < 0)
{
Console.WriteLine("a1 小于 a2");
}
else if (result > 0)
{
Console.WriteLine("a1 大于 a2");
}
判断结果
Hello, World!
hello3hello2
a1 大于 a2
四、不等于的使用
String a1 = "hello3";
string a2 = "hello2";
Console.WriteLine(a1 + a2);
;
if (a1 != a2)
{
Console.WriteLine("两个字符串bu相等");
}
else
{
Console.WriteLine("两个字符串相等");
}
判断结果
Hello, World!
hello3hello2
两个字符串bu相等