forked from 131/lab0.1_letscontinue
13
This commit is contained in:
2
Makefile
2
Makefile
@@ -1,6 +1,6 @@
|
||||
OBJ = str.o str_test.o util.o
|
||||
|
||||
CFLAGS = -Wall
|
||||
CFLAGS = -Wall
|
||||
|
||||
TARGET=myprog
|
||||
|
||||
|
||||
68
str.c
68
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;
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
BIN
str_test.o
BIN
str_test.o
Binary file not shown.
Reference in New Issue
Block a user