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?
myString == new String(myString.Reverse().ToArray());
\$\endgroup\$char
type, and in was indeed annoying. But later I learned of theStringInfo
class which handles splitting a string into text elements. Using it a unicode aware solution is barely more complex than the naive approach. \$\endgroup\$