C# Programming Interview Questions Tutorial
C# Interview Question: Check If String is Palindrome
In this interview question you have to find out if any given string is palindrome or not.
Method 1:
In this method, we will find the first half of the string and compare each character with the second half of string in reverse order. If any of the string doesn't match, then it is not a palindrome.
using System;
class Program {
static void Main() {
Console.WriteLine("IsWordPalindrome uoo: " + IsWordPalindrome("uoo"));
Console.WriteLine("IsWordPalindrome noon: " + IsWordPalindrome("uoou"));
Console.WriteLine("IsWordPalindrome uooou: " + IsWordPalindrome("uooou"));
Console.WriteLine("IsWordPalindrome uobobou: " + IsWordPalindrome("uobobou"));
Console.WriteLine("IsWordPalindrome uofsdfsoou: " + IsWordPalindrome("uofsdfsoou"));
Console.WriteLine("IsWordPalindrome uosfsoou: " + IsWordPalindrome("uosfsoou"));
Console.WriteLine("IsWordPalindrome kayak: " + IsWordPalindrome("kayak"));
}
static bool IsWordPalindrome(string word){
bool isPalindrome = true;
// Convert word to array of chars
char[] charArr = word.ToCharArray();
// method 1
// find first half and compare to second half
int loop = charArr.Length/2;
for(int i=0; i < loop; i++){
if(charArr[i] != charArr[(charArr.Length - 1)-i]){
isPalindrome = false;
break;
}
}
return isPalindrome;
}
}
Method 2:
In this method we will reverse the array and create string and compare to original one. Althod this one is less efficient then the first method.