From a459d34d124a2993a313d29cf8b84a5d0df42e87 Mon Sep 17 00:00:00 2001 From: mrb0nk500 Date: Wed, 27 Jul 2022 15:35:15 -0300 Subject: misc: Add `find_delm()`, and `get_str_delm_range()` `find_delm()` finds the first matched delimiter of the supplied delimiter(s), and either returns the pointer to the first non-delimiter character after the match, or the match itself if `skip_delm` is true, or false respectivly. `get_str_delm_range()` finds, and returns the string in between the supplied starting, and ending delimiter(s). It also returns the pointer to the first non-delimiter character after the end of the range in `rhs`. --- misc.c | 33 +++++++++++++++++++++++++++++++++ misc.h | 2 ++ 2 files changed, 35 insertions(+) diff --git a/misc.c b/misc.c index af40bff..8246ba1 100644 --- a/misc.c +++ b/misc.c @@ -69,6 +69,39 @@ char *get_line(char **str) { } } +char *find_delm(char *str, const char *delm, int skip_delm) { + if (!is_empty(str)) { + const size_t span = strcspn(str, delm); + return &str[(skip_delm) ? strspn(&str[span], delm) : span]; + } else { + return NULL; + } +} + +char *get_str_delm_range(char *str, const char *start_delm, const char *end_delm, char **rhs) { + if (!is_empty(str)) { + char *start = find_delm(str, start_delm, 1); + char *end; + char *dummy; + rhs = (rhs != NULL) ? rhs : &dummy; + + for (end = start; *end != '\0'; end += strcspn(end, end_delm)) { + if (*end++ == '\\') { + end += strspn(end, end_delm); + continue; + } else { + break; + } + } + + *end++ = '\0'; + *rhs = end; + return start; + } else { + return NULL; + } +} + char *make_str(const char *str) { const size_t length = strlen(str); char *s = calloc(length+1, sizeof(char)); diff --git a/misc.h b/misc.h index 82291a1..0ad5fba 100644 --- a/misc.h +++ b/misc.h @@ -2,6 +2,8 @@ #define MISC_H extern char *read_file(const char *filename, long *size); +extern char *find_delm(char *str, const char *delm, int skip_delm); +extern char *get_str_delm_range(char *str, const char *start_delm, const char *end_delm, char **rhs); extern char *get_line(char **str); extern char *make_str(const char *str); extern char *dir_path_num(const char *root, int num); -- cgit v1.2.3-13-gbd6f