65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (3 votes)

Feb 3, 2011

CPOL
viewsIcon

23702

downloadIcon

4

I prefer this technique (uses less memory and may be faster, but requires slightly more code):public bool IsPalindrome(string str, StringComparison comparisonType){ bool valid = true; int halfway = str.Length / 2; int lastIndex = str.Length - 1; for (int i = 0; i <...

I prefer this technique (uses less memory and may be faster, but requires slightly more code):
public bool IsPalindrome(string str, StringComparison comparisonType)
{
    bool valid = true;
    int halfway = str.Length / 2;
    int lastIndex = str.Length - 1;
    for (int i = 0; i < halfway; i++)
    {
        if (!str.Substring(i, 1).Equals(str.Substring(lastIndex - i, 1), comparisonType))
        {
            valid = false;
            break;
        }
    }
    return valid;
}
You can then provide an overload to avoid passing in the comparison type:
public bool IsPalindrome(string str)
{
    return IsPalindrome(str, StringComparison.OrdinalIgnoreCase);
}