Last active
June 16, 2022 22:12
-
-
Save Ximaz/91a83eec79a23fd78d29119a118786a9 to your computer and use it in GitHub Desktop.
A string replace implementation in C
This file contains hidden or 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
#include <stdlib.h> | |
#include <string.h> | |
char *replace_with(char *dest, char const *old, char const *new) | |
{ | |
size_t tail_len = 0; | |
size_t old_len = strlen(old); | |
size_t new_len = strlen(new); | |
char *match; | |
while ((match = strstr(dest, old))) { | |
tail_len = strlen(match + old_len); | |
memmove(match + new_len, match + old_len, tail_len + 1); | |
memcpy(match, new, new_len); | |
} | |
return dest; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment