In C: How to fix the code below so it remove the char from the original string n
ID: 3825184 • Letter: I
Question
In C: How to fix the code below so it remove the char from the original string not just print the other char.
#include<stdio.h> //Header Files
int main()
{
void rmchr(char[],char); //Function Declaration String,Character passing into function
char s1[]= "abracadabra"; //s1 to abracadabra
char s2[]= "abracadabra"; //s2 to abracadabra
char s3[]= "abracadabra"; //s3 to abracadabra
char s4[]= "aaaa"; //s4 to aaaa
char s5[]= "aaaa"; //s5 to aaaa
printf("String Character Answer ");
printf("%s ",s1); //Printing String Before Passing
rmchr(s1,'a'); //Passing String and Character to remove into rmchr function
printf("%s ",s2); //Printing String Before Passing
rmchr(s2,'b'); //Passing String and Character to remove into rmchr function
printf("%s ",s3); //Printing String Before Passing
rmchr(s3,'n'); //Passing String and Character to remove into rmchr function
printf("%s ",s4); //Printing String Before Passing
rmchr(s4,'a'); //Passing String and Character to remove into rmchr function
printf("%s ",s5); //Printing String Before Passing
rmchr(s5,'n'); //Passing String and Character to remove into rmchr function
return 0;
}
void rmchr(char str[],char ch) //Function Definition
{
char *p; //Pointer Variable
p=&str[0]; //Storing address of First character of String in *p
printf("%c ",ch); //Printing Character to remove
while(*p!='') //Loop for iterating String
{
if(*p!=ch)
{ //Checking if Character is not equal to each character
printf("%c",*p); //Prints that unequal character
}
p++; //Address Increment of *p
}
printf(" ");
}
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
int *getcharcountarray(char *str)
{
int *count=(int *)calloc(sizeof(int),no_of_chars);
int i;
for(int i=0;*(str+i);i++)
count [*(str+i)]++;
return count;
}
char *removechar(char *str,char *mask_str)
{
int *count=getcharcountarray(mask_arr);
int ip_ind=0,res_ind=0;
while(*(str+ip_ind))
{
char temp=*(str+ip_ind);
if(count[temp]==0)
{
*(str+res_ind)=*(str+ip_ind);
res_ind++;
}
ip_ind++;
}
*(str+res_ind)='';
}return str;
'}
int main()
{
char str[]="abracadabra";
char mask_str[]="aaaa";
printf("%s",removedirtychars(str,mask_str));
return 0;
}