-1

is there a practical method to replace all occurrences of % with %% in the following string

char * str = "%s %s %s";

printf("%s",str);

so the result is:

 %%s %%s %%s

or must I be using a function which scans each character in the string until it finds %, then replaces it with %% ?

Shallon
  • 35
  • 3
  • 4
    There's no such function in the standard library so, yes, you have to write your own. –  Jul 28 '17 at 07:58
  • 2
    First of all, since string literals can not be changed, it is necessary to allocate an array with allowance or to allocate another array. – BLUEPIXY Jul 28 '17 at 08:00
  • 2
    Possible duplicate of [What is the function to replace string in C?](https://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c) – phd Jul 28 '17 at 08:20

1 Answers1

0

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;
}
VolAnd
  • 6,367
  • 3
  • 25
  • 43