A palindrome is a group of characters or a word that reads the same if we read from left to right and right to left. An example of a palindrome string is the word "MALAYALAM". The order of the characters is the same when we read from left and right.
In this post, I'll explain three different ways to check if a string is a palindrome or not in C#.
Examples
Here are some more examples of a palindrome.
- Lol
- Wow
- Level
- Radar
- Peep
- Mom
- Noon
- Eye
1) Using Reverse() Method
The easiest way to solve this problem is to use the string Reverse() method. In this method, we're comparing the original string with the reverse of the string in an if conditional statement.
Console.WriteLine("Enter any word");
string text = Console.ReadLine();
string reverse = string.Join("", text.Reverse());
if(text == reverse)
{
Console.WriteLine("Palindrome");
}
else
{
Console.WriteLine("Not palindrome");
}
2) Reverse using for loop
The second method is to use a for loop to iterate over the string starting from the last character to find the reverse and then compare it with the original string.
Use this method if you don't want to use any built-in string methods.
Console.WriteLine("Enter any word");
string text = Console.ReadLine();
string reverse = string.Empty;
for (int i = text.Length - 1; i >= 0; i--)
{
reverse += text[i];
}
if (text == reverse)
{
Console.WriteLine("Palindrome");
}
else
{
Console.WriteLine("Not Palindrome");
}
3) Without finding the reverse of the string
Unlike the first two methods, we don't have to find the reverse of the string in this method. Instead, we're directly checking the first character with the last character, the second character with the second-last character, and so on.
Console.WriteLine("Enter any word");
string text = Console.ReadLine();
int length = text.Length - 1;
bool hasMismatch = false;
for (int i = 0; i < text.Length; i++)
{
if(text[i] != text[length - i])
{
hasMismatch = true;
break;
}
}
if (hasMismatch)
{
Console.WriteLine("Not palindrome");
}
else
{
Console.WriteLine("Palindrome");
}
Conclusion
In this post, we learned three different ways to check if the given string is a palindrome or not in C#. If you would like to share any other methods, please share them in the comments.