I have a string as input and have to break the string in two substrings. If the left substring equals the right substring then do some logic.
How can I do this?
protected bool CheckIfPalindrome(string text)
{
if (text != null)
{
string strToUpper = Text.ToUpper();
char[] toReverse = strToUpper.ToCharArray();
Array.Reverse(toReverse );
String strReverse = new String(toReverse);
if (strToUpper == toReverse)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Use this the sipmlest way.
Out of all the solutions, below can also be tried:
public static bool IsPalindrome(string s)
{
return s == new string(s.Reverse().ToArray());
}
static void Main(string[] args)
{
string str, rev="";
Console.Write("Enter string");
str = Console.ReadLine();
for (int i = str.Length - 1; i >= 0; i--)
{
rev = rev + str[i];
}
if (rev == str)
Console.Write("Entered string is pallindrome");
else
Console.Write("Entered string is not pallindrome");
Console.ReadKey();
}
string test = "Malayalam";
char[] palindrome = test.ToCharArray();
char[] reversestring = new char[palindrome.Count()];
for (int i = palindrome.Count() - 1; i >= 0; i--)
{
reversestring[palindrome.Count() - 1 - i] = palindrome[i];
}
string materializedString = new string(reversestring);
if (materializedString.ToLower() == test.ToLower())
{
Console.Write("Palindrome!");
}
else
{
Console.Write("Not a Palindrome!");
}
Console.Read();
Just for fun:
return myString.SequenceEqual(myString.Reverse());
public bool Solution(string content)
{
int length = content.Length;
int half = length/2;
int isOddLength = length%2;
// Counter for checking the string from the middle
int j = (isOddLength==0) ? half:half+1;
for(int i=half-1;i>=0;i--)
{
if(content[i] != content[j])
{
return false;
}
j++;
}
return true;
}