patterncsharpMajor
Check a string to see if it is a palindrome
Viewed 0 times
palindromecheckstringsee
Problem
I have written two code pieces to check if a given string is a palindrome:
Please tell me which one is better.
Is there a better method than this?
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.
That being said, an actual review is in order.
- 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
IsSomethingorHasSomething. A great name would beIsPalindrome.
- 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 thefor` 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.