The Program in C# Program to Check If the first two characters and last two characters of a given string are same or not is given below:
using System;
namespace StringCheck
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter a string here to check if first two characters and last two characters are same:");
string inputString = Console.ReadLine();
bool areSame = false;
if (inputString.Length >= 2)
{
string firstTwo = inputString.Substring(0, 2);
string lastTwo = inputString.Substring(inputString.Length - 2);
if (firstTwo == lastTwo)
{
areSame = true;
}
}
if (areSame)
{
Console.WriteLine("The first two characters and last two characters are same!");
}
else
{
Console.WriteLine("The first two characters and last two characters are not same!");
}
Console.ReadLine();
}
}
}
Output:
Hello Codeauri Family, enter a string here to check if first two characters and last two characters are same:comoco
The first two characters and last two characters are same!
Pro-Tips💡
Here are the step by step execution of above program:
- Imports the
System
namespace. - Defines a
namespace
calledStringCheck
. - Defines a class called
Program
inside theStringCheck
namespace. - Defines a
Main
method inside theProgram
class. This method is the entry point of the program. - The program prompts the user to enter a string.
- Reads the input string and stores it in a variable
inputString
. - Initializes a boolean variable
areSame
to false. - Checks if the length of
inputString
is greater than or equal to 2. - If the length is greater than or equal to 2, the program extracts the first two characters of
inputString
and stores it infirstTwo
. It also extracts the last two characters ofinputString
and stores it inlastTwo
. - The program then checks if
firstTwo
andlastTwo
are equal. If they are equal, it setsareSame
to true. - The program then checks the value of
areSame
. IfareSame
is true, the program prints “The first two characters and last two characters are same!”. IfareSame
is false, the program prints “The first two characters and last two characters are not same!”. - The program waits for the user to press the Enter key before ending.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.