import libc {...} | |
struct StrLinesIter { | |
next: char const*; | |
start: char const*; | |
end: char const*; | |
} | |
func str_lines(str: char const*): StrLinesIter { | |
return {next = str}; | |
} | |
func str_lines_next(iter: StrLinesIter*): bool { | |
if (!*iter.next) { | |
return false; | |
} | |
iter.start = iter.next; | |
iter.end = iter.next; | |
while (*iter.end && *iter.end != '\n') { | |
iter.end++; | |
} | |
iter.next = *iter.end ? iter.end + 1 : iter.end; | |
return true; | |
} | |
struct StrWordsIter { | |
next: char const*; | |
start: char const*; | |
end: char const*; | |
} | |
func str_words(str: char const*): StrWordsIter { | |
return {next = str}; | |
} | |
func str_words_next(iter: StrWordsIter*): bool { | |
iter.start = iter.next; | |
while (isspace(*iter.start)) { | |
iter.start++; | |
} | |
if (!*iter.start) { | |
return false; | |
} | |
iter.end = iter.start; | |
while (*iter.end && !isspace(*iter.end)) { | |
iter.end++; | |
} | |
iter.next = *iter.end ? iter.end + 1 : iter.end; | |
return true; | |
} | |
struct StrTokensIter { | |
next: char const*; | |
delims: char const*; | |
start: char const*; | |
end: char const*; | |
} | |
func str_tokens(str: char const*, delims: char const*): StrTokensIter { | |
return {next = str, delims = delims}; | |
} | |
func str_contains(str: char const*, c: char): bool { | |
while (*str) { | |
if (*str == c) { | |
return true; | |
} | |
str++; | |
} | |
return false; | |
} | |
func str_tokens_next(iter: StrTokensIter*): bool { | |
iter.start = iter.next; | |
while (str_contains(iter.delims, *iter.start)) { | |
iter.start++; | |
} | |
if (!*iter.start) { | |
return false; | |
} | |
iter.end = iter.start; | |
while (*iter.end && !str_contains(iter.delims, *iter.end)) { | |
iter.end++; | |
} | |
iter.next = *iter.end ? iter.end + 1 : iter.end; | |
return true; | |
} | |
func main(argc: int, argv: char**): int { | |
str := " first\n\n \nsecond\nthird"; | |
for (it := str_lines(str); str_lines_next(&it)) { | |
printf("'%.*s'\n", it.end - it.start, it.start); | |
} | |
str = " first second\r third\n\t fourth "; | |
for (it := str_words(str); str_words_next(&it)) { | |
printf("'%.*s'\n", it.end - it.start, it.start); | |
} | |
for (it := str_tokens(str, " \t\n\r"); str_tokens_next(&it)) { | |
printf("'%.*s'\n", it.end - it.start, it.start); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment