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

View File

@@ -1,6 +1,6 @@
OBJ = str.o str_test.o util.o
CFLAGS = -Wall
CFLAGS = -Wall
TARGET=myprog

BIN
myprog

Binary file not shown.

68
str.c
View File

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

BIN
str.o

Binary file not shown.

View File

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

Binary file not shown.