📌  相关文章
📜  使用等于 (==) 运算符检查给定字符串是否相等的 C# 程序

📅  最后修改于: 2022-05-13 01:54:55.860000             🧑  作者: Mango

使用等于 (==) 运算符检查给定字符串是否相等的 C# 程序

给定两个字符串,我们需要使用 ==运算符检查它们是否相等。 == 运算符比较引用标识,即它们是否引用堆中的相同标识。如果它们相等,则返回 true,否则返回 false。

例子:

Input
String 1 : geeks
String 2 : geeks
Output   : Equal

Input
String 1 : geeks
String 2 : geeqs
Output   : Not Equal

方法:

示例 1:

C#
// C# program to check given strings are
// equal or not. Using == operator
using System;
 
class GFG{
     
public static void Main()
{
    string str1 = "geeks";
    string str2 = "geeks";
     
    // Here we use == operator to check
    // the equality of the strings
    Console.WriteLine(str1 == str2);
}
}


C#
// C# program to check given strings
// are equal or not. Using == operator
using System;
 
class GFG{
     
public static void Main()
{
    string str1 = "geeks";
    string str2 = "geeqs";
     
    // Here we use == operator to check
    // the equality of the strings
    Console.WriteLine(str1 == str2);
}
}


C#
// C# program to check given strings
// are equal or not. Using == operator
using System; 
 
class GFG{
     
static void Main(string[] args) 
{
    object str1 = "geeks";  
    object str2 = new string("geeks");      
     
    Console.WriteLine(str1 == str2); 
}      
}



输出
True

示例 2:

C#

// C# program to check given strings
// are equal or not. Using == operator
using System;
 
class GFG{
     
public static void Main()
{
    string str1 = "geeks";
    string str2 = "geeqs";
     
    // Here we use == operator to check
    // the equality of the strings
    Console.WriteLine(str1 == str2);
}
}
输出
False

但是,当我们比较引用标识不相同的字符串时,==运算符可能无法按预期工作。让我们借助以下示例来理解:

C#

// C# program to check given strings
// are equal or not. Using == operator
using System; 
 
class GFG{
     
static void Main(string[] args) 
{
    object str1 = "geeks";  
    object str2 = new string("geeks");      
     
    Console.WriteLine(str1 == str2); 
}      
} 
输出
False