From: Holger Schemel Date: Mon, 19 Feb 2024 22:35:44 +0000 (+0100) Subject: added function to split string by separator characters to array X-Git-Tag: 4.4.0.0-test-1~340 X-Git-Url: https://git.artsoft.org/?a=commitdiff_plain;h=861cfc1e558b662eb474a7b0dbc7e406eea2fa9e;p=rocksndiamonds.git added function to split string by separator characters to array --- diff --git a/src/libgame/misc.c b/src/libgame/misc.c index 536d90b5..0f4cab03 100644 --- a/src/libgame/misc.c +++ b/src/libgame/misc.c @@ -1239,6 +1239,62 @@ void setString(char **old_value, const char *new_value) *old_value = getStringCopy(new_value); } +char **getSplitStringArray(const char *s, const char *separators, int max_tokens) +{ + const char *s_ptr, *s_last = s; + byte separator_table[256] = { FALSE }; + int num_tokens; + char **tokens = NULL; + + if (s == NULL) + return NULL; + + if (separators == NULL) + return NULL; + + if (max_tokens < 1) + max_tokens = INT_MAX; + + // if string is empty, return empty array + if (*s == '\0') + { + tokens = checked_malloc(sizeof(char *)); + tokens[0] = NULL; + + return tokens; + } + + // initialize separator table for all characters in separators string + for (s_ptr = separators; *s_ptr != '\0'; s_ptr++) + separator_table[*(byte *)s_ptr] = TRUE; + + // count number of tokens in string + for (num_tokens = 1, s_ptr = s; *s_ptr != '\0'; s_ptr++) + if (separator_table[*(byte *)s_ptr] && num_tokens < max_tokens) + num_tokens++; + + // allocate array for determined number of tokens + tokens = checked_malloc((num_tokens + 1) * sizeof(char *)); + + // copy all but last separated sub-strings to array + for (num_tokens = 0, s_ptr = s; *s_ptr != '\0'; s_ptr++) + { + if (separator_table[*(byte *)s_ptr] && num_tokens + 1 < max_tokens) + { + tokens[num_tokens++] = getStringCopyN(s_last, s_ptr - s_last); + s_last = s_ptr + 1; + } + } + + // copy last separated sub-string to array + tokens[num_tokens++] = getStringCopyN(s_last, s_ptr - s_last); + + // terminate array + tokens[num_tokens] = NULL; + + return tokens; +} + boolean strEqual(const char *s1, const char *s2) { return (s1 == NULL && s2 == NULL ? TRUE : diff --git a/src/libgame/misc.h b/src/libgame/misc.h index 2893ba0f..cee6c113 100644 --- a/src/libgame/misc.h +++ b/src/libgame/misc.h @@ -181,6 +181,7 @@ char *getStringCopyN(const char *, int); char *getStringCopyNStatic(const char *, int); char *getStringToLower(const char *); void setString(char **, const char *); +char **getSplitStringArray(const char *s, const char *, int); boolean strEqual(const char *, const char *); boolean strEqualN(const char *, const char *, int); boolean strEqualCase(const char *, const char *);