HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Check a string to see if it is a palindrome

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
palindromecheckstringsee

Problem

I have written two code pieces to check if a given string is a palindrome:

public static bool FirstMethod(string str)
{
    int i = 0;
    int j = str.Length - 1;

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

        i++;
        j--;
    }

    return true;
}


public static bool SecondMethod(string myString)
{
    string first = myString.Substring(0, myString.Length / 2);
    char[] arr = myString.ToCharArray();
    Array.Reverse(arr);
    string temp = new string(arr);
    string second = temp.Substring(0, temp.Length / 2);
    return first.Equals(second);
}


Please tell me which one is better.

Is there a better method than this?

Solution

I would prefer the first one for a few reasons.

  • It's more readable and easily understandable in my opinion.



  • There's only one string, so less overhead. (Which is negligible unless this is being called a lot.)



  • There's only one array. Reverse creates a second array.



That being said, an actual review is in order.

  • Methods that return a boolean value should have names of the form IsSomething or HasSomething. A great name would be IsPalindrome.



  • Neither method accepts anything but a string. Numbers can be palindromic too. Wouldn't it be a nice addition if we could pass an integer to it as well? (Without explicitly calling .ToString() before passing it in that is.)



  • I like that you're only checking for i



  • I also like the while loop. It's a lot cleaner than the for` loop suggested by another answer.



  • I won't speak much on the second method, because I think @elios provided a nice implementation of it.

Context

StackExchange Code Review Q#58395, answer score: 25

Revisions (0)

No revisions yet.