C# Program - Check whether a String is Palindrome or not


Advertisements

A string is known as a Palindrome string if the reverse of the string is same as the string. For example, 'radar' is a palindrome string, but 'rubber' is is not a palindrome string.

Example: Check Palindrome String

In the below example, the string called MyString is checked for palindrome string. A while loop is used to compare the characters of the string. Two variable l and r are created which initially points to first and last character of the string. If the compared characters are not same, it will increase the variable flag by one and exit the loop, else the loop is continued. After each iteration, l is increased by one and r i s decreased by one until they cross each other. Finally, based on value of flag variable, MyString is checked for palindrome string.

using System;

namespace MyApplication { 
   class MyProgram {
    static void Palindrome(String MyString) {
      int l = 0;
      int r = MyString.Length - 1;
      int flag = 0;
      while(r > l){
        if (MyString[l] != MyString[r]){
          flag = 1;
          break;
        }
        l++;
        r--;
      }
      if (flag == 0){
        Console.WriteLine(MyString + " is a Palindrome string.");
      }
      else{
        Console.WriteLine(MyString + " is not a Palindrome string.");
      }
    }

    static void Main(String[] args) {
      Palindrome("radar");
      Palindrome("rubber");
      Palindrome("malayalam");
    }
  }
}

Output

radar is a Palindrome string.
rubber is not a Palindrome string.
malayalam is a Palindrome string.



Recommended Pages


Advertisements