65.9K
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Feb 15, 2011

CPOL
viewsIcon

8986

downloadIcon

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)
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 !=