I'm trying to check a palindrome string, which one do you thing is better?
I created a bool function to check the Palindrome and then in Main we implemented the user input along with the if statement which checks if bool1 is true or false determining the output, respectively if the string is a palindrome or not.
public static bool Palindrome(string text)
{
if (text.Length <= 1)
return true;
else
{
if ( text[0] != text[ text.Length - 1 ] )
return false;
else
return Palindrome( text.Substring( 1, text.Length-2 ) );
}
}
public static void Main()
{
string userInput;
bool bool1;
Console.Write(" Input a string : ");
userInput = Console.ReadLine();
bool1 = Palindrome(userInput);
if (bool1 ==true)
{
Console.WriteLine(" The string is Palindrome.");
}
else
{
Console.WriteLine(" The string is not a Palindrome.");
}
}
or this one
static void Main(string[] args)
{
Console.WriteLine("Please input a string");
string userString = Console.ReadLine();
string userOutput = Reversed(userString);
bool res = CheckPalindrome(userString, userOutput);
Console.ReadKey();
}
static string Reversed(string userString)
{
char[] reveresed = userString.ToCharArray();
Array.Reverse(reveresed);
string userOutput = new string(reveresed);
return userOutput;
}
static bool CheckPalindrome(string userOutput, string userString)
{
bool bool1 = userString.Equals(userOutput, StringComparison.OrdinalIgnoreCase);
if (bool1 == true)
{
Console.WriteLine("The string " + userOutput + " is a Palindrome!");
}
else
{
Console.WriteLine("The string " + userOutput + " is not a Palindrome!");
}
return bool1;
}
As @TimSchmelter said, the second version is faster and more readable.
There is however, a faster if more complex, version than either of those two.
Loop through the first half of the string, and compare it with the second half. The middle character in an odd-numbered length will be ignored.
bool IsPalindrome(string myString)
{
if (string.IsNullOrEmpty(myString))
return false;
for (var i = 0; i < myString.Length / 2; i++)
{
if(myString[i] != myString[myString.Length - i - 1])
return false;
}
return true;
}