// Helper function inline char * Shuffle(char *dest, const char *src) { return (char *) memmove(dest, src, lstrlen(src) + sizeof(char)); } void Replace(char *buf, const size_t size, const char *szFrom, const char *szTo) { char * p; int len = lstrlen(buf); const int lenFrom = lstrlen(szFrom); const int lenTo = lstrlen(szTo); const int diff = lenTo - lenFrom; for (;;) { if ((p = strstr(buf, szFrom)) == NULL) break; if (len + diff > (int)size - 1) { break; } Shuffle(p + lenTo, p + lenFrom); strncpy(p, szTo, lenTo); len += diff; } }
Programming Tips - Plain C: replace a string in a string
Date: 2014dec3
Language: C
Q. Plain C: replace a string in a string
A. Here is a nice function for that: