You should understand that replacement cannot be made in the same str
, because increase number of characters will require more memory. So before replacement number of replacement must be counted.
The following function allows to make any replacement a single character to string (set of characters).
char *replace(const char *s, char ch, const char *repl) {
// counting the number of future replacements
int count = 0;
const char *t;
for(t=s; *t; t++)
{
count += (*t == ch);
}
// allocation the memory for resulting string
size_t rlen = strlen(repl);
char *res = malloc(strlen(s) + (rlen-1)*count + 1);
if(!res)
{
return 0;
}
char *ptr = res;
// making new string with replacements
for(t=s; *t; t++) {
if(*t == ch) {
memcpy(ptr, repl, rlen); // past sub-string
ptr += rlen; // and shift pointer
} else {
*ptr++ = *t; // just copy the next character
}
}
*ptr = 0;
// providing the result (memory allocated in this function
// should be released outside this function with free(void*) )
return res;
}
For your particular task this function can be used as
char * str = "%s %s %s";
char * newstr = replace(str, '%', "%%");
if( newstr )
printf("%s",newstr);
else
printf ("Problems with making string!\n");
Pay attention, that new string is stored in the heap (dynamic memory allocated with respect to size of initial string and number of replacements), so the memory should be reallocated when newstr
is not needed anymore, and before program goes out the scope of newstr
pointer.
Just think over a place for
if( newstr )
{
free(newstr);
newstr = 0;
}