Skip to content

Instantly share code, notes, and snippets.

@bg5sbk
Created April 18, 2014 18:30
Show Gist options
  • 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;
}
@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