Skip to content

Instantly share code, notes, and snippets.

@bg5sbk
Created April 18, 2014 18:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bg5sbk/11058000 to your computer and use it in GitHub Desktop.
Save bg5sbk/11058000 to your computer and use it in GitHub Desktop.
replace string in C
// fork from https://github.com/irl/la-cucina/blob/master/str_replace.c
char* str_replace(char* string, const char* substr, const char* replacement) {
char* tok = NULL;
char* newstr = NULL;
char* oldstr = NULL;
int oldstr_len = 0;
int substr_len = 0;
int replacement_len = 0;
newstr = strdup(string);
substr_len = strlen(substr);
replacement_len = strlen(replacement);
if (substr == NULL || replacement == NULL) {
return newstr;
}
while ((tok = strstr(newstr, substr))) {
oldstr = newstr;
oldstr_len = strlen(oldstr);
newstr = (char*)malloc(sizeof(char) * (oldstr_len - substr_len + replacement_len + 1));
if (newstr == NULL) {
free(oldstr);
return NULL;
}
memcpy(newstr, oldstr, tok - oldstr);
memcpy(newstr + (tok - oldstr), replacement, replacement_len);
memcpy(newstr + (tok - oldstr) + replacement_len, tok + substr_len, oldstr_len - substr_len - (tok - oldstr));
memset(newstr + oldstr_len - substr_len + replacement_len, 0, 1);
free(oldstr);
}
free(string);
return newstr;
}
@solsticedhiver
Copy link

solsticedhiver commented Apr 26, 2020

There is an infinite loop if you try to double a char:

str_replace("test_test", "_" "__");

expected output "test__test", result is infinite loop because you try to replace from the start of the newly created string at each step

The outcome is the same if you try to replace the subtring with the same string, meaning:

str_replace("test", "e", "e"); // infinite looop

@kwakd
Copy link

kwakd commented Nov 17, 2020

i love u

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment