In: Computer Science
Write a C program for the recursive algorithm that removes all occurrences of a specific character from a string. (please comment the code)
#include <stdio.h>
#include <string.h>
void deletechar(char *s,char c)
{
static int i=0,k=0; // for not creating again
if(!s[i])// if s[i] become null return
{
return;
}
else
{
s[i]=s[i+k];// store s[i+k] into
s[i]
if(s[i]==c)// check if s[i] equal to target
character
{
k++;//increase k to next
index
i--;// decrease i to previous
index
}
i++;// if not the target character increase i
deletechar(s,c);// again call deletechar till s[i]
reaches null
}
}
int main()
{
char s[1000],c; // create string and variable c
printf("Enter the string : ");
gets(s); // get string
printf("Enter character: ");
c=getchar(); // get character to be deleted
deletechar(s,c); // call function
printf("string after removing all occurance of character
:'%c'\n",c);
printf("%s",s); // print string after removing character
return 0;
}
/* PLEASE UPVOTE */