Skip to content

Replace Char In String

A C function that returns a new string with every occurrence of one character replaced by another.

Published May 24, 1996

The single-character version of find-and-replace: walk the input once, copy each character as-is unless it matches the target, in which case emit the substitute. The original implementation allocates a fresh buffer with malloc and returns it (so the caller owns the memory), leaving the input untouched. Handy for quick cleanups - turning * delimiters into spaces, stripping control characters, masking digits - anywhere you need a character-level substitution without pulling in a regex engine.

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

char *Replace(char *, char, char);

int main()
{
	char *String;

	String = Replace("Hello*My*Little*Cruel*World",'*',' ');

	printf("%s\n",String);

	system("pause");
	return 0;
}

///////////////////////////////////////////////////////////////////////

//6/3/1999
char *Replace(char *xInputString, char xReplace, char xWith)
{
	DWORD StringLength = strlen(xInputString);
	DWORD LocalLoop = 0;

	char *WorkingString;
	char InputString[StringLength];

	sprintf(InputString,"%s",xInputString);

	WorkingString = (char *) malloc(StringLength);

	while(LocalLoop != StringLength)
	{
		if(InputString[LocalLoop] != xReplace)
			WorkingString[LocalLoop] = InputString[LocalLoop];
		else
			WorkingString[LocalLoop] = xWith;
		LocalLoop++;
	}

	return WorkingString;
}

Two things to fix if you reuse this: the result is never null-terminated (the loop runs exactly StringLength times and stops), so add WorkingString[StringLength] = '\0'; before returning; and the author's own later note in the source shows the modern one-liner that does the same job in place - for(;*s;*s++){*s=*s==o?n:*s;}.

An unhandled error has occurred. Reload 🗙