diff --git a/Makefile b/Makefile index c47f71d..ecf0998 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ OBJ = str.o str_test.o util.o -CFLAGS = -Wall +CFLAGS = -Wall TARGET=myprog diff --git a/myprog b/myprog index 89a528f..fd5a6f3 100755 Binary files a/myprog and b/myprog differ diff --git a/str.c b/str.c index 98ebaf0..eeac533 100644 --- a/str.c +++ b/str.c @@ -152,34 +152,46 @@ str_sub(str *s, int start_idx, int length) return s2; } + // Hint: you can create temporary string object! -int -str_replace(str *s, char *substr, char *replacement) +int str_replace(str *s, char *substr, char *replacement) { - assert(s && substr && replacement); - int substr_len = strlen(substr); - int replacement_len = strlen(replacement); - int count = 0; - - str temp; - str_init(&temp); - - int pos = 0; - int found_pos; - - while ((found_pos = str_find(s, substr)) != -1) { - str_append_n(&temp, s->ptr + pos, found_pos - pos); - str_append(&temp, replacement); - pos = found_pos + substr_len; - count++; - } - - if (pos < s->len) { - str_append_n(&temp, s->ptr + pos, s->len - pos); - } - - str_set(s, str_data(&temp)); - str_deinit(&temp); - - return count; + assert(s && substr && replacement); + int substr_len = strlen(substr); + int count = 0; + + str temp; + str_init(&temp); + + int pos = 0; + int found_pos; + + found_pos = str_find(s, substr); + + while (found_pos != -1) { + str_append_n(&temp, s->ptr + pos, found_pos - pos); + str_append(&temp, replacement); + + pos = found_pos + substr_len; + count++; + + str search_str; + str_init(&search_str); + str_append_n(&search_str, s->ptr + pos, s->len - pos); + found_pos = str_find(&search_str, substr); + if (found_pos != -1) { + found_pos += pos; + } + str_deinit(&search_str); + } + + if (pos < s->len) { + str_append_n(&temp, s->ptr + pos, s->len - pos); + } + + str_set(s, str_data(&temp)); + + str_deinit(&temp); + + return count; } diff --git a/str.o b/str.o index f5f12e1..84b7e6d 100644 Binary files a/str.o and b/str.o differ diff --git a/str_test.c b/str_test.c index 9df506a..935d361 100644 --- a/str_test.c +++ b/str_test.c @@ -99,6 +99,7 @@ test_it() "str_sub, не правильная строка %s", str_data(&s2)); str_deinit(&s2); + //TEST str_init //TEST str_replace str_set(&s, "foo bar baz foo"); str_replace(&s, "foo", "test"); diff --git a/str_test.o b/str_test.o index 4b7811a..c2f9923 100644 Binary files a/str_test.o and b/str_test.o differ