c#判断字符串相等
时间: 2023-07-26 17:16:24 浏览: 167
在 C# 中,可以使用 `==` 运算符来判断两个字符串是否相等。例如:
```csharp
string str1 = "Hello";
string str2 = "Hello";
if (str1 == str2)
{
Console.WriteLine("str1 和 str2 相等");
}
else
{
Console.WriteLine("str1 和 str2 不相等");
}
```
注意:在 C# 中,字符串是引用类型,因此使用 `==` 运算符比较的是两个字符串对象的引用地址,而不是字符串的内容。如果要比较字符串的内容,可以使用 `string.Equals` 方法或者 `String.Compare` 方法。
相关问题
c#怎么判断字符串相等
在C#中,可以使用Equals方法来比较两个字符串是否相等。示例代码如下:
```
string str1 = "hello";
string str2 = "world";
string str3 = "hello";
if(str1.Equals(str2))
{
Console.WriteLine("str1和str2相等");
}
else
{
Console.WriteLine("str1和str2不相等");
}
if(str1.Equals(str3))
{
Console.WriteLine("str1和str3相等");
}
else
{
Console.WriteLine("str1和str3不相等");
}
```
输出结果为:
```
str1和str2不相等
str1和str3相等
```
除了Equals方法,还可以使用“==”运算符来比较两个字符串是否相等,示例代码如下:
```
string str1 = "hello";
string str2 = "world";
string str3 = "hello";
if(str1 == str2)
{
Console.WriteLine("str1和str2相等");
}
else
{
Console.WriteLine("str1和str2不相等");
}
if(str1 == str3)
{
Console.WriteLine("str1和str3相等");
}
else
{
Console.WriteLine("str1和str3不相等");
}
```
输出结果与上面的示例代码相同。
C#判断字符串是否相等
在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()`方法,都可以用来判断两个字符串是否相等。选择哪种方式取决于你的具体需求和编程习惯。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)