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.00/5 (3 votes)
6 Feb 2011CPOL 23.6K   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):

C#
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:

C#
public bool IsPalindrome(string str)
{
    return IsPalindrome(str, StringComparison.OrdinalIgnoreCase);
}

License

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