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
|
OBJ = str.o str_test.o util.o
|
||||||
|
|
||||||
CFLAGS = -Wall
|
CFLAGS = -Wall
|
||||||
|
|
||||||
TARGET=myprog
|
TARGET=myprog
|
||||||
|
|
||||||
|
|||||||
68
str.c
68
str.c
@@ -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;
|
|
||||||
|
found_pos = str_find(s, substr);
|
||||||
while ((found_pos = str_find(s, substr)) != -1) {
|
|
||||||
str_append_n(&temp, s->ptr + pos, found_pos - pos);
|
while (found_pos != -1) {
|
||||||
str_append(&temp, replacement);
|
str_append_n(&temp, s->ptr + pos, found_pos - pos);
|
||||||
pos = found_pos + substr_len;
|
str_append(&temp, replacement);
|
||||||
count++;
|
|
||||||
}
|
pos = found_pos + substr_len;
|
||||||
|
count++;
|
||||||
if (pos < s->len) {
|
|
||||||
str_append_n(&temp, s->ptr + pos, s->len - pos);
|
str search_str;
|
||||||
}
|
str_init(&search_str);
|
||||||
|
str_append_n(&search_str, s->ptr + pos, s->len - pos);
|
||||||
str_set(s, str_data(&temp));
|
found_pos = str_find(&search_str, substr);
|
||||||
str_deinit(&temp);
|
if (found_pos != -1) {
|
||||||
|
found_pos += pos;
|
||||||
return count;
|
}
|
||||||
|
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_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");
|
||||||
|
|||||||
BIN
str_test.o
BIN
str_test.o
Binary file not shown.
Reference in New Issue
Block a user