0

See my code below:

string s1 = "madam";
string s2 = string.Empty;

int length = s1.Length - 1;
for (int i = length; i >= 0; i--)
{
   s2 += s1[i];
}
if (s1 == s2)
{
   Console.WriteLine("Palindrome");
}
else
{
   Console.WriteLine("Not Palindrome");
}
thatguy
  • 21,059
  • 6
  • 30
  • 40
User202818
  • 11
  • 2

2 Answers2

0

for finding palindrome, you can use

public static void Main()
{
    string s1 = "madams";
    string response = s1==Reverse(s1)?"palindrome":"not palindrome";
    Console.WriteLine(response);
}
public static string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

Ref: Reverse String

Mihir Dave
  • 3,954
  • 1
  • 12
  • 28
0

The code you provided runs fine, but you can improve it. At the moment you create numerous new string instances each time you add character, because strings are immutable.

s2 += s1[i];

These allocations are expensive. You can check the string by comparing the first with the last character, then the second with the second last, or in general index i with text.Length - i - 1:

private bool IsPalindrome(string text)
{
   for (var i = 0; i < text.Length / 2; i++)
   {
      if (text[i] != text[text.Length - i - 1])
         return false;
   }

   return true;
}
thatguy
  • 21,059
  • 6
  • 30
  • 40