Here is how I solved this problem (though this is not the only nor the best way by any means) for an assignment where it was also requisite to determine if a string was a reverse prefix of the other.
Obviously a palindrome is a reverse prefix of itself so if you can determine a reverse prefix then you can determine a palindrome.
I would love some feedback on my code as well as any thoughts on my implementation/solution.
int main()
{
char string1[50];
char string2[50];
printf("Please enter a string: ");
gets(string1);
if (strlen(string1) == 1)
exit(1);
printf("Please enter a second string: ");
gets(string2);
printf("\nString 1 = %s", string1);
printf("\nString 2 = %s\n", string2);
if (isReversePrefix(string1, string2))
printf("String 2 is a reversed prefix of string 1\n");
if (isPalindrome(string1))
printf("String 1 is a palindrome\n");
else
printf("String 1 is not a palindrome\n");
if (isPalindrome(string2))
printf("String 2 is a palindrome\n");
else
printf("String 2 is not a palindrome\n");
return 0;
}
/************************************************
isReversePrefix - Receives two string pointers
and determines if the second is a reverse
prefix of the first. Returns either true or
false.
The word 'HIM' has the following prefixes 'H', 'HI',
'HIM'. All of these can be reversed to 'H', 'IH', 'MIH'
************************************************/
int isReversePrefix(char *str1, char *str2)
{
char *temp1 = str1;
char *temp2 = str2;
if (strlen(str2) > strlen(str1))
return 0;
strrev(temp2);
while ((*temp1 == *temp2) && (*temp2 != '\0'))
{
temp1++;
temp2++;
}
if (*temp2 == '\0')
return 1;
else
return 0;
}
/************************************************
isPalindrome - receives one string parameter and
checks if it is a palindrome or not. Returns
true if it is and false if not.
************************************************/
int isPalindrome(char *str1)
{
char *start = str1;
char *end = str1 + strlen(str1) - 1;
if (isReversePrefix(start, end))
return 1;
else
return 0;
}
str2.strlen()
??? what kind of C code is this? I'm having a hard time believing this compiles... \$\endgroup\$temp2.strrev();
. \$\endgroup\$