Write a C# sharp Program to check wheather the given string is Palindrome or not. (Ex: LEVEL is palindrome).Don't use inbuild string functions.

 Posted by Nagasundar_Tn on 11/30/2012 | Category: C# Interview questions | Views: 7673 | Points: 40
Answer:

PALINDROME string is sequence of letters that is the same forward as backward. Example is LEVEL.

class Program

{
public bool IsPalindrome(string sInput)
{
int iLengthofInput = 0;

//Find Length of the string.
foreach(char chr in sInput)
iLengthofInput++;

char[] sArrReverse = new char[iLengthofInput];

int iIncr =iLengthofInput-1;
foreach(char chr in sInput)
{
sArrReverse[iIncr] = chr;
iIncr--;
}

string sRevString = new string(sArrReverse);

#region AnotherWay for string initializng
//string sRevString = "";
//for(int i = 0; i < iLengthofInput; i++)
//{
// sRevString += sArrReverse[i];
//}
#endregion

if (sRevString == sInput)
return true;
else
return false;

}
static void Main(string[] args)
{
Program pObj = new Program();
Console.WriteLine(pObj.IsPalindrome("LEVEL");
Console.Read();
}
}


In the above code I am finding the length of the string. For example : LEVEL - length is 5.

char[] sArrReverse = new char[iLengthofInput];


int iIncr =iLengthofInput-1;
foreach(char chr in sInput)
{
sArrReverse[iIncr] = chr;
iIncr--;
}

In the above code I am creating the arrary called "sArrReverse" and initializing with length of input string.
In Foreach loop I am assigning values of input string in reverse order. So now sArrReverse contains "LEVEL" which is reverse form of original input string "LEVEL".
I am creating a string "sRevString" and initializing with "sArrReverse" value in the following code
 string sRevString = new string(sArrReverse);

OR
string sRevString = "";

for(int i = 0; i < iLengthofInput; i++)
{
sRevString += sArrReverse[i];
}


Using If condition I am checking both strings and returning the value depends on condition.


Asked In: SGS Interview | Alert Moderator 

Comments or Responses

Login to post response