It uses strpos from the eXtended Standard C Library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | char *str_replace(const char *find, const char *replace, const char *source, char *buffer) { int i = 0, p = 0, c = 0; size_t find_len = strlen(find); size_t replace_len = strlen(replace); size_t source_len = strlen(source); while ((c = strpos(find, source, i++)) >= 0) { strncpy(buffer+strlen(buffer), source+p, c-p); strncpy(buffer+strlen(buffer), replace, replace_len); p = c + find_len; } strncpy(buffer+strlen(buffer), source+p, source_len - p); buffer[strlen(buffer)] = '\0'; return buffer; } |
Usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #define BUF_SIZE 255 int main(void) { char text[255] = " finding all spaces in this string is a fun, i guess? "; char buf[BUF_SIZE]; memset(buf, 0, BUF_SIZE); str_replace(" ", "==", text, buf); printf("buf = \"%s\"\n", buf); return 0; } |
Output:
buf = “==finding==all==spaces==in==this==string==is==a==fun,==i==guess?==”