I have made a program to test if the string entered is a palindrome or not. Here's the source code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void clrsp(char *);
void rev(const char *,char *);
int main()
{
char str1[80],str2[80];
printf("Enter a string: ");
fgets(str1,80,stdin);
str1[strlen(str1)-1]='\0'; //eliminate newline
clrsp(str1); //clear spaces and punctuation marks
rev(str1,str2); //reverse the string
/*Use strcmp to check if two strings are same*/
if(strcmp(str1,str2)==0) printf("%s is a palindrome!\n",str1);
else printf("%s is not a palindrome!\n",str1);
return 0;
}
/*Clear spaces and punctuations marks*/
void clrsp(char *s)
{
int i=0,j=0;
int n;
n=strlen(s);
while(i<n)
{
while(!(isalnum(s[j]))) j++; //next character
if(j>=n) break; //break if it exceeds the array size
s[i]=s[j];
i++;
j++;
}
s[i]='\0'; //append terminating character
}
/*Reverse string*/
void rev(const char *s1,char *s2)
{
int i=0,j;
int n;
n=strlen(s1);
j=n-1;
while(i<n)
{
while(!(isalnum(s1[j]))) j--; //previous character
if(j<0) break; //break if it exceeds the array size
s2[i]=s1[j];
i++;
j--;
}
s2[i]='\0'; //append terminating character
}
The program clears all the spaces and punctuation marks using clrsp().
It then reverse the string using rev().
Finally it uses strcmp() to check if two strings are same.
First of all, I would like to know how can I improve the palindrome program. Am I doing it the stupid way? Are there any better ways?
Second, how can I make a program that uses a recursive function to identify palindromes? I do not even have the faintest idea on how to achieve this?
Thanks!