String program #2
(Compare
two string)
Enter a string1: liveviar
Enter a string2: liveviar
Strings are equal.
The program for the string program is
written in C# programming language and will accept a two string as input. The
loops will iterate based on the entry of string and compare the first string
with the second string and return the output in Boolean type.
Let’s find out a simple and easy way
to code the program.
Practical Implementation:
using System;
namespace patternProblem.String
{
class String2 //compare two string
{
static void Main(string[] args)
{
Console.Write("Enter a string1: ");
string str1 = Console.ReadLine();
Console.Write("Enter a string2: ");
string str2 = Console.ReadLine();
//Method-1 (Using in-built CompareTo() function)
if
(str1.CompareTo(str2) == 0)
{
Console.WriteLine("Strings are equal.");
}
else
{
Console.WriteLine("Strings are not equal.");
}
//Method-2 (Using if-else condition)
if
(str1 == str2)
{
Console.WriteLine("Strings are equal.");
}
else
{
Console.WriteLine("Strings are not equal.");
}
//Method-3 (Using ternary operator)
string result = (str1 == str2) ? "Strings are equal." : "Strings are not
equal.";
Console.WriteLine(result);
Console.ReadKey();
}
}
}
Output:
The input string1
here is “liveviar” and string2 is “liveviar”. So, based on the string
comparison it will return whether the strings are equal or not. The output is
shown below:
Enter a string1: liveviar
Enter a string2: liveviar
Strings are equal.
Press any key to continue . . .
For any
query, comment us below.
Skip to
Main Table String based program
Keep learning and sharing...
No comments:
Post a Comment