This commit is contained in:
etrushko05
2025-10-25 04:35:31 -04:00
parent 93f4d98839
commit 3b7ddda0f5
6 changed files with 42 additions and 29 deletions

BIN
myprog

Binary file not shown.

56
str.c
View File

@@ -152,34 +152,46 @@ str_sub(str *s, int start_idx, int length)
return s2; return s2;
} }
// Hint: you can create temporary string object! // Hint: you can create temporary string object!
int int str_replace(str *s, char *substr, char *replacement)
str_replace(str *s, char *substr, char *replacement)
{ {
assert(s && substr && replacement); assert(s && substr && replacement);
int substr_len = strlen(substr); int substr_len = strlen(substr);
int replacement_len = strlen(replacement); int count = 0;
int count = 0;
str temp; str temp;
str_init(&temp); str_init(&temp);
int pos = 0; int pos = 0;
int found_pos; int found_pos;
while ((found_pos = str_find(s, substr)) != -1) { found_pos = str_find(s, substr);
str_append_n(&temp, s->ptr + pos, found_pos - pos);
str_append(&temp, replacement);
pos = found_pos + substr_len;
count++;
}
if (pos < s->len) { while (found_pos != -1) {
str_append_n(&temp, s->ptr + pos, s->len - pos); str_append_n(&temp, s->ptr + pos, found_pos - pos);
} str_append(&temp, replacement);
str_set(s, str_data(&temp)); pos = found_pos + substr_len;
str_deinit(&temp); count++;
return 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;
} }

BIN
str.o

Binary file not shown.

View File

@@ -99,6 +99,7 @@ test_it()
"str_sub, не правильная строка %s", str_data(&s2)); "str_sub, не правильная строка %s", str_data(&s2));
str_deinit(&s2); str_deinit(&s2);
//TEST str_init
//TEST str_replace //TEST str_replace
str_set(&s, "foo bar baz foo"); str_set(&s, "foo bar baz foo");
str_replace(&s, "foo", "test"); str_replace(&s, "foo", "test");

Binary file not shown.