MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
09_replace.c

Write your own function in the library's shape: StrViews in, a Str to append to, a bool out.

/* Together: write your own function with views in and a Str out. */
#include "mem/mem.c"
#include "str/str.c"
#include <stdio.h>
#include <stdlib.h>
/* Append `text` to `out` with every `from` replaced by `to`. */
static bool replace_all(Str *out, StrView text, StrView from, StrView to) {
size_t at;
while ((at = sv_find(text, from)) != SV_NPOS) {
if (!str_append(out, sv_slice(text, 0, at)) || !str_append(out, to)) {
return false;
}
text = sv_slice(text, at + from.len, text.len);
}
return str_append(out, text);
}
int main(void) {
Str out = { 0 };
if (!replace_all(&out, SV("Rodya went out. Rodya came back."), SV("Rodya"),
SV("Raskolnikov"))) {
str_free(&out);
return EXIT_FAILURE;
}
printf("%.*s\n", STR_FMT(out));
/* Appending a Str to itself is safe: str_append handles the overlap. */
if (!str_append(&out, str_view(&out))) {
str_free(&out);
return EXIT_FAILURE;
}
printf("%zu bytes after doubling\n", out.len);
str_free(&out);
return EXIT_SUCCESS;
}
size_t len
Number of bytes in the view.
Definition str.h:74
size_t len
Bytes of content, excluding the terminator.
Definition str.h:66
size_t sv_find(StrView v, StrView needle)
Index of the first needle in v.
Definition str.c:237
#define SV(lit)
View of a string literal, with its length computed at compile time.
Definition str.h:80
StrView str_view(const Str *s)
Borrow the whole of s.
Definition str.c:212
#define STR_FMT(s)
printf helper: printf("%.*s", STR_FMT(s)) prints exactly len bytes.
Definition str.h:85
#define SV_NPOS
Returned by the find functions when there is no match.
Definition str.h:217
void str_free(Str *s)
Free the buffer and reset s to the zero state.
Definition str.c:50
bool str_append(Str *s, StrView v)
Append v.
Definition str.c:89
StrView sv_slice(StrView v, size_t from, size_t to)
Bytes from up to but not including to.
Definition str.c:268
Owned, growable byte string.
Definition str.h:64
Non-owning view of bytes; handy for passing slices and literals around.
Definition str.h:72