Recursive C String replace -
i'm quite new c programming, used use c++ string class, i'm wondering how go doing recursive replacement of string string.
my code this, doesn't seem work correctly , cannot quite pin down fails. works fine on 1 replacement, more 1 , fails.
#include <stdio.h> #include <string.h> char *replace_str(char *str, char *orig, char *rep) { int current_index = 0; static char buffer[10000]; if (!strstr(str, orig)) // 'orig' in 'str'? { return str; } while (1) { char *p; if (!(p = strstr(str + current_index, orig))) // 'orig' in 'str'? { return buffer; } strncpy(buffer, str, p-str); // copy characters 'str' start 'orig' st$ buffer[p-str] = '\0'; sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig)); printf("%d -> %s\n", current_index, buffer); current_index = (p - str) + strlen(rep); str = buffer; } return buffer; } int main(void) { puts(replace_str("hello world world", "world", "world2")); return 0; }
with example, prints this:
0 -> hello world2 world 12 -> hello world2 world22 hello world2 world22
it not best implementation, here find stringreplace function task.
about code. first, better caller supplies dest buffer instead of having static buffer function. then, not check buffer overflow.
your
strncpy(buffer, str, p-str); // copy characters 'str' start 'orig' st$
will copy a except in first iteration. not good, buffer shouldn't overlap. use memmove
instead.
but whole idea not clean since update same buffer use source catch other occurrences.
at point overwrite input (when str , buffer points same thing) loosing information since replacing word longer original replaced not preserve "original next character". (if try "work" instead of "world2", should work)...
so current_index should index original string str (and you'll never str = buffer), , append internal buffer part need (up occurence of "world" if found append "world2", update current_index length of "world" , go on).
i (trying keep original idea, more or less)
#include <stdio.h> #include <string.h> char *replace_str(char *str, const char *orig, const char *rep) { size_t buf_index = 0; static char buffer[10000]; if (!strstr(str, orig)) // 'orig' in 'str'? { return str; } buffer[0] = 0; for(;;) { char *p; if (!(p = strstr(str, orig))) { strcpy(buffer + buf_index, str); return buffer; } strncpy(buffer + buf_index, str, p - str); strcpy(buffer + buf_index + (p - str), rep); buf_index += (p-str) + strlen(rep); str = p + strlen(orig); } return buffer; } int main(void) { puts(replace_str("hello world world world", "wor", "world2")); return 0; }
Comments
Post a Comment