Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

To check string is palindrome or not in .NET (C#)

4.50/5 (2 votes)
15 Feb 2011CPOL 9K   2  
Yet another way to do this. This might not be as short the other alternates and might not look elegant, but at least it only needs two int variables and doesn't create any extra objects (reference types)bool IsPalindrome(string stringToCheck, bool ignoreCase) { if...
Yet another way to do this. This might not be as short the other alternates and might not look elegant, but at least it only needs two int variables and doesn't create any extra objects (reference types)
C#
bool IsPalindrome(string stringToCheck, bool ignoreCase) 
{
    if (string.IsNullOrEmpty(stringToCheck))
        return false;

    for (int i = 0, j = stringToCheck.Length - 1; i < j; ++i, --j)
    {
        if (ignoreCase)
        {
            if (char.ToLowerInvariant(stringToCheck[i]) != char.ToLowerInvariant(stringToCheck[j]))
                return false;
        }
        else 
        {
            if (stringToCheck[i] != stringToCheck[j])
                return false;
        }
    }
    return true;
}

EDIT: Changed !Equals to !=

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)