Monday, April 24, 2017

C ++ code to find if a string is a palindrome

A string is called a palindrome if it reads the same if they read both forward and backward. For eg:



All the above words spell the same when read forward and backward and are called as palindromes. The following code takes a input string and finds you whether the string is a palindrome or not.

To find if string is a palindrome or not we will start comparing the characters using two pointers, one titrating from the beginning and other from the end of the string. At each step we will increment the pointer that starts from the beginning by one character and decrementing the pointer that starts from the end by one character. At any step if the comparison returns a false that is characters don't match then we can conclude that the sting is not a palindrome.

The following figure shows the same steps for finding if the string CIVIC is a palindrome or not.



The pointer passed to the function , str, will be pointing to the beginning of the string. To get a new pointer pointing to the end of string, we will assign the value of new pointer to



where len is the length of the string. We do len-1 to skip comparing the null character.

We can start comparing the rev and st, and only len/2 comparisons are enough cause once we reach the middle of the string we would have covered the whole string as shown the example above.

Thus the full code in c++ for finding out if a string is palindrome or not is

 
#include&ltiostream&gt 
#include&ltcstring&gt 
using namespace std;

void palindrome(char *st){
int len=strlen(st);
cout << len << "\n";
bool palin=1;
char *rev;
rev=(st+(len-1)); 
for(int i=0;i&ltlen/2;i++){
	if(*(st++) != *(rev--)) {
		palin=0;
		break;
		}
}
if(palin){
	cout <<"The string is a palindrome\n";
}
else {
	cout <<"The string is not a palindrome\n";
}
	
}


int main() {
char str[20];
cout << "Enter the string to be checked \n";
cin >> str; 
if(strlen(str)>10) {
	cout <<"String length excedded\n";
	return -1;
}
palindrome(str);
return 0;
}

No comments:

Post a Comment