Skip to content

Replace String In String

A C function that replaces every occurrence of a substring with another substring, building the result into a caller-supplied buffer.

Published Oct 17, 1998

The multi-character companion to Replace Char In String. It scans the source one position at a time; wherever strncmp finds the search string it appends the replacement and jumps past the match, otherwise it copies the single current character into the target. The result is assembled in a buffer you provide, so the size is your responsibility - make it comfortably larger than the input when the replacement is longer than the search term. Useful for normalizing delimiters, rewriting tokens in config text, or any global substring substitution without regex.

#include <Windows.H>
#include <Stdio.H>
#include <Stdlib.H>

int Replace(char *xString, char *xReplace, char *xWith, char *xTarget)
{
	const char *p = NULL;

    	if (xString == NULL || xTarget == NULL)
 		return 1;

    	for (p = xString; *p; ++p)
		{
			if (strncmp(p, xReplace, strlen(xReplace)) == 0)
			{
				strcat(xTarget, xWith);
	    			p += strlen(xReplace) - 1;
	 		} else strncat(xTarget, p, 1);
		}
		return 0;
}

int main()
{
	char MyString[1234];
	Replace("Hello-Cruel-World","-"," ",MyString);
	printf("MyString = %s\n",MyString);
	return 0;
}

Notes before reusing: zero-initialize xTarget first (the function appends with strcat/strncat, it does not start from scratch), and be aware this performs overlapping-match scanning - after a replacement it resumes from the next original position, which is the usual behavior but worth knowing if your search terms can nest inside each other.

An unhandled error has occurred. Reload 🗙