Palindrome string program in C
Problem
Write a C++ algorithm that takes a string as input then check if the input string is Palindrome. A Palindrome string reads the same from left to right and from right to left as in the following example: Rats live on no evil star
Solution
We need one pass through the characters of the string to get the string length or use a built in function to get that. Once the length of the string is found then one loop can be used to compare the first character with the last character and the second character with the one before the last character and so on until the string is entirely checked. If we can find only one occurrence where two compared characters are not the same ignoring the case then the string is not Palindrome. The number of iterations needed is half the string length. If the string has an odd number of characters then the character in the middle of the string is not going to be compared with any other character.
Example code
Here is a simple C++ program code to do that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
//Includes #include <iostream> using namespace std; int main () { //Sample string or character array char str[] = "Rats live on no evil star"; //Find the length of string. int len = 0; while (str[len] != '\0') { len++; } //Compare the first character with the last //character and the second character with //the one before the last character and so //on but you need to pay attention to the //fact that comparison can not be done before //converting the string to either lower case //letters or upper case letters. You can use //a built in function to do that but we used a //manual method to convert the string. for (int i = 0; i < len/2; i++) { //Manually convert the characters to lowercase if((str[i] >= 65) && (str[i] <= 90)) { str[i] = str[i] + 32; } if((str[len-i-1] >= 65) & (str[len-i-1] <= 90)) { str[len-i-1] = str[len-i-1] + 32; } //If one difference is found then it is not a Palindrome if (str[i] != str[len-i-1]) { cout << "String is not Palindrome"; return 1; } } cout << "String is Palindrome"; return 0; } |