c - replacing all occurences of % with %% ?, need a function? -
is there practical method replace occurrences of % %% in following string
char * str = "%s %s %s"; printf("%s",str); so result is:
%%s %%s %%s or must using function scans each character in string until finds %, replaces %% ?
you should understand replacement cannot made in same str, because increase number of characters require more memory. before replacement number of replacement must counted.
the following function allows make replacement single character string (set of characters).
char *replace(const char *s, char ch, const char *repl) { // counting number of future replacements int count = 0; const char *t; for(t=s; *t; t++) { count += (*t == ch); } // allocation memory 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 replacements for(t=s; *t; t++) { if(*t == ch) { memcpy(ptr, repl, rlen); // past sub-string ptr += rlen; // , shift pointer } else { *ptr++ = *t; // copy next character } } *ptr = 0; // providing result (memory allocated in function // should released outside function free(void*) ) return res; } for particular task function can used as
char * str = "%s %s %s"; char * newstr = replace(str, '%', "%%"); if( newstr ) printf("%s",newstr); else printf ("problems making string!\n"); pay attention, new string stored in heap (dynamic memory allocated respect size of initial string , number of replacements), memory should reallocated when newstr not needed anymore, , before program goes out scope of newstr pointer.
just think on place for
if( newstr ) { free(newstr); newstr = 0; }
Comments
Post a Comment