insideNinja insideNinja - 3 months ago 11
C Question

Function that removes unwanted character from string

I need to make a function that takes a string and a character, the function needs to remove all the occurrences of the character in the string and returns the total number of characters removed. I have managed to modify the string as to be able to remove the unwanted character but I can't seem to be able to replace the old string with the new one. Thanks for any replies in advance.

This is what I've managed so far:

int clearstr(char *st,char u){
int i,j=0,total=0,size=strlen(st);
char *new_str=calloc(size,sizeof(char));
for(i=0;i<size;i++){
if(st[i]!=u){
new_str[j]=st[i];
j++;}
else total++;
}
new_str[j]='\0';
printf("%s",new_str);

//until here all is good ,new_str has the modified array that i want but i can't find a way to replace the string in st with the new string in new_str and send it back to the calling function (main),thanks for any help //

return total;
}

Answer

You create a new string but you are not using it yet you can use a function like memcpy or strcpy to copy the contents, take a look at the copying strings documentation. You also don't deallocate the memory of the calloc call, this creates a memory leak. Try something like:

...
new_str[j]='\0';
printf("%s",new_str);

strcpy(st, new_str); // Copy the contents of the new string to the original one
free(new_str); // Clear the memory of the allocation in this function, otherwise you get a memory leak

return total; 
...