Created
April 18, 2014 18:30
-
-
Save bg5sbk/11058000 to your computer and use it in GitHub Desktop.
replace string in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is an infinite loop if you try to double a char:
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: