MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
05_split.c

Split fields with sv_split_next() and words with sv_token_next(), and see how they treat empty pieces.

/* StrView on its own: split fields and tokens. */
#include "mem/mem.c"
#include "str/str.c"
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* Split keeps empty fields: the right tool for CSV-like data. */
StrView rest = SV("Raskolnikov,Sonya,,Dunya,");
StrView field;
while (sv_split_next(&rest, SV(","), &field)) {
printf("field [%.*s]\n", STR_FMT(field));
}
/* Token skips runs of delimiters: the right tool for words. */
rest = SV(" Pale, feverish and restless. ");
StrView word;
while (sv_token_next(&rest, SV(" ,."), &word)) {
printf("word [%.*s]\n", STR_FMT(word));
}
return EXIT_SUCCESS;
}
#define SV(lit)
View of a string literal, with its length computed at compile time.
Definition str.h:80
bool sv_token_next(StrView *rest, StrView delims, StrView *token)
strtok without the mutation: skip delims, then cut the next run of other bytes.
Definition str.c:306
#define STR_FMT(s)
printf helper: printf("%.*s", STR_FMT(s)) prints exactly len bytes.
Definition str.h:85
bool sv_split_next(StrView *rest, StrView sep, StrView *piece)
Cut the piece before sep off rest.
Definition str.c:286
Non-owning view of bytes; handy for passing slices and literals around.
Definition str.h:72