Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 %% ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
146 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!
");

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...