OneBite.Dev - Coding blog in a bite size

Check If A String Is A Palindrome In C#

Code snippet for how to Check If A String Is A Palindrome In C# with sample and detail explanation

Palindromes are words or phrases that read the same backward as forward, such as “madam” or “racecar.” In this article, we will go through a simple C# program to check if a string is a palindrome.

Code snippet: Palindrome Checker in C#

Here is the simple code snippet for the function that checks if a string is a palindrome or not in C#.

public static bool IsPalindrome(string str)
{
    str = str.ToLower();
    int i = 0, j = str.Length - 1;
    
    while (i < j)
    {
        if (str[i] != str[j])
           return false;

        i++;
        j--;
    }
    
    return true;
}

You can call this function with any string you want to check as follows:

string word = "madam";
bool result = IsPalindrome(word);
Console.WriteLine($"Is the word {word} a palindrome? " + result);

Code Explanation for: Palindrome Checker in C#

Let’s walk through the code to understand it better:

Step 1: The function IsPalindrome is declared with a string parameter named ‘str’.

public static bool IsPalindrome(string str)

Step 2: We convert the string to lower case so that the function can handle words irrespective of their case.

str = str.ToLower();

Step 3: We define two indices, ‘i’ is initialized to the start of the string (0) and ‘j’ to the end of the string (str.Length - 1).

int i = 0, j = str.Length - 1;

Step 4: A while loop is used to traverse from both ends towards the middle. If at any point the characters at index ‘i’ and ‘j’ are not equal, we return false indicating that the string is not a palindrome.

while (i < j)
{
    if (str[i] != str[j])
       return false;

    i++;
    j--;
}

Step 5: If the loop completes successfully without returning false, it means the string is a palindrome and we return true.

return true;

So, this simple C# code can easily check if a string is a palindrome or not. You can use this function in any of your applications where you want to make such checks.

c-sharp