Hello.
I'm very new to C and I decided to make a function called str_replace which replaces strings inside strings which have been made using malloc. It appears to work but can anyone find any room for improvements.
Any advice will be appreciated. I'd like to know if people think finding the number of occurrences to calculate the new string size was a good idea and if my use of pointers makes sense.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * str_replace(char * string,char * find,char * replace){
//Replaces each occurence of a particular string inside a malloc-made string with another string
char * pos = string;
size_t replace_size = strlen(replace);
size_t find_size = strlen(find);
size_t excess = replace_size - find_size;
//Get number of occurences
int x = 0;
while (1) {
pos = strstr(pos,find);
if (pos == NULL){
break;
}
pos++;
x++;
}
if (!x){ //No occurences so return with original string
return string;
}
char * new_string = malloc(sizeof(char)*(strlen(string) + excess*x + 1)); //Plus 1 for null termination
pos = string; //Reset pointer
char * string_track = string; //Used to move around string.
char * new_string_begin = new_string; //Begining of new string to return
while (1) {
pos = strstr(pos,find);
if (pos == NULL){
strcpy(new_string,string_track); //Fill in remainder
break;
}
pos++;
size_t seg_len = pos-string_track; //Length between found string and last
strncpy(new_string,string_track,seg_len); //Copy string to just before pos
new_string += seg_len - 1; //Go to point for replacement by adding what was added to pointer.
strncpy(new_string,replace,replace_size);
new_string += replace_size; //Go to point after what was replaced
string_track = pos + find_size - 1; //Original string should go to point after found string.
}
free(string); //Remove old string
return new_string_begin; //return new string
}
int main (int argc, const char * argv[]) {
char * string = malloc(sizeof(char)*21);
strcpy(string,"No,yes,no,yes,no,yes");
printf("%s\n",string);
string = strreplace(string, "no", "nope");
printf("%s\n",string);
free(string);
string = malloc(sizeof(char)*21);
strcpy(string,"No,yes,no,yes,no,yes");
printf("%s\n",string);
string = strreplace(string, "hello", "nope");
printf("%s\n",string);
free(string);
string = malloc(sizeof(char)*21);
strcpy(string,"No,yes,no,yes,no,yes");
printf("%s\n",string);
string = strreplace(string, "yes", "y");
printf("%s\n",string);
free(string);
return 0;
}