C#判断字符串是否相等
时间: 2023-08-15 22:13:31 浏览: 94
在C#中,你可以使用`==`运算符或者`Equals()`方法来判断两个字符串是否相等。
使用`==`运算符:
```csharp
string str1 = "Hello";
string str2 = "World";
if (str1 == str2)
{
Console.WriteLine("字符串相等");
}
else
{
Console.WriteLine("字符串不相等");
}
```
使用`Equals()`方法:
```csharp
string str1 = "Hello";
string str2 = "World";
if (str1.Equals(str2))
{
Console.WriteLine("字符串相等");
}
else
{
Console.WriteLine("字符串不相等");
}
```
无论是使用`==`运算符还是`Equals()`方法,都可以用来判断两个字符串是否相等。选择哪种方式取决于你的具体需求和编程习惯。
相关问题
c#判断字符串是否相等
在 C# 中,我们可以使用 `==` 运算符或者 `string.Equals` 方法来判断两个字符串是否相等。
1. 使用 `==` 运算符
```csharp
string str1 = "hello";
string str2 = "world";
string str3 = "hello";
if (str1 == str2)
{
Console.WriteLine("str1 equals str2");
}
else
{
Console.WriteLine("str1 does not equal str2");
}
if (str1 == str3)
{
Console.WriteLine("str1 equals str3");
}
else
{
Console.WriteLine("str1 does not equal str3");
}
```
输出结果为:
```
str1 does not equal str2
str1 equals str3
```
2. 使用 `string.Equals` 方法
```csharp
string str1 = "hello";
string str2 = "world";
string str3 = "hello";
if (string.Equals(str1, str2))
{
Console.WriteLine("str1 equals str2");
}
else
{
Console.WriteLine("str1 does not equal str2");
}
if (string.Equals(str1, str3))
{
Console.WriteLine("str1 equals str3");
}
else
{
Console.WriteLine("str1 does not equal str3");
}
```
输出结果同样为:
```
str1 does not equal str2
str1 equals str3
```
需要注意的是,在比较字符串时,应该使用 `string.Equals` 方法,因为它可以指定比较的方式(如大小写敏感或不敏感),而 `==` 运算符则只是比较两个字符串的值是否相等。
C#判断2字符串是否相等
在C#中,可以使用`==`运算符来判断两个字符串是否相等。例如:
```csharp
string str1 = "hello";
string str2 = "world";
string str3 = "hello";
if (str1 == str2)
{
Console.WriteLine("str1 equals str2");
}
else
{
Console.WriteLine("str1 does not equal str2");
}
if (str1 == str3)
{
Console.WriteLine("str1 equals str3");
}
else
{
Console.WriteLine("str1 does not equal str3");
}
```
输出为:
```
str1 does not equal str2
str1 equals str3
```
注意,在C#中,字符串是引用类型,所以比较字符串时应该使用`==`运算符而不是`Equals()`方法。