I want to write a program that will take substrings from a given string.
Then, the program will check if the substrings are palindrome. If palindrome, it will list them anywhere else and then it will sort out the unique palindromes.
But is there any process so that I can put more than one strings in an array individually??
I have written a program that will count, how many of the substrings are palindrome but, I cannot figure out how to count unique palindromes from them.
My code is here below:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
char* substring(char*,int,int);
int is_palindrome(char array[],int length);
int main()
{
char string[85],*pointer;
int position,length,temp,string_length,pesky;
printf("enter a string\n");
while(gets(string)){
position=1,length=2;
temp=string_length=pesky=strlen(string);
while(position<=string_length){
while(length<=temp){
pointer=substring(string,position,length);
if(is_palindrome(pointer,length)==1){pesky++;puts(pointer);}
free(pointer);
length++;
}
position++;
temp--;
length=2;
}
printf("The string '%s' contains %d palindromes.\n",string,pesky);
}
return 0;
}
char* substring(char *string,int position,int length)
{
char *pointer;
int c;
pointer=malloc(length+1);
if(pointer==NULL){
printf("unable to locate memory.\n");
exit(EXIT_FAILURE);
}
for(c=0;c<position-1;c++){
string++;
}
for(c=0;c<length;c++){
*(pointer+c)=*string;
string++;
}
*(pointer+c)='\0';
return pointer;
}
int is_palindrome(char array[],int length)
{
int k,j,o=0;
for(k=length-1,j=0;k>j;k--,j++){
if(array[k]!=array[j]){
o=1;
break;
}
}
if (o==0) {return 1;}
else {return 0;}
}
In order to store the various substrings, you will need an array of char pointers. As you separate out your substrings, which you are copying into a malloced memory area, you take the pointer that is returned and store the pointer into your array of char pointers.
So something like the following will define an array of chars along with a count of the number of char pointers that are currently in the array.
At this point you will have an array of char pointers. You can then do a search through the array to determine if the palindrome has already been found. Something like the following.
The above
strcmp()function is case sensitive so you might want to use the case insensitive compare.I have not tried compiling this code so there may be an error in it however this would be a general approach that should get you close to what you want.
Once you are done, you can then loop over the array and do a
free()to free the malloced memory.