Code to test if a string is palindrome. The string can contain any number of spaces, punctuations ('.', '?', '!', ','), case sensitive. The code will work for strings like
"madam",
"racecar",
"radar"
But won't work for
"a man a plan a canal panama",
"a man a pla n a cana L Panama",
"Cigar? Toss it in a can, It is sotragic"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char string[100];
printf("Enter a string: ");
scanf("%[^\n]", string);
int isPalindrome = 1; // assign 0 to this if the string is a NOT palindrome
// code to test if string is a palindrome
char str1[100], str2[100];
int len = strlen(string) - 1;
int i;
for (i = 0; i <= len; i++) {
if (string[i] == '?' || string[i] == '.' || string[i] == '!' || string[i] == ',' || string[i] == ' ') {
i++;
}
strcpy(str1, string);
}
int length = strlen(str1) - 1;
int j, k;
for (j = length; j >= 0; j--) {
str2[j] = str1[len - j];
}
k = strcmp(str2, str1);
// at the end you need to test
if (k == 0) {
printf("Yes, it is Palindrome!\n");
} else {
printf("No, not a Palindrome\n");
}
return 0;
}
You need to clean your input string to remove all non-alphabetic characters. You code looks pretty lost on this, but it's a straightforward task of copying over only desired characters (and converting all desired characters to the same case) to a new string.
Be sure to null terminate this new string.
If we test this with:
We see:
Having solved this problem, your palindrome logic should now be easier. All programming problems are when you break them down into smaller problems.