Dave's Brain

Browse - Programming Tips - In plain C, how can I replace a string in a string?

Date: 2014dec3
Language: C


Q.  In plain C, how can I replace a string in a string?

A.  Here is a nice function for that:

// 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); int lenFrom = lstrlen(szFrom); int lenTo = lstrlen(szTo); 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; } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.