From e4f25d99846528d965fe41b895a4bb37e7028114 Mon Sep 17 00:00:00 2001 From: twinaphex Date: Thu, 9 Jun 2016 08:01:55 +0200 Subject: [PATCH] Add new versions of whitespace trimming functions --- libretro-common/include/string/stdstring.h | 9 ++++ libretro-common/string/stdstring.c | 49 ++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/libretro-common/include/string/stdstring.h b/libretro-common/include/string/stdstring.h index 604d66d488..8faf2ba25c 100644 --- a/libretro-common/include/string/stdstring.h +++ b/libretro-common/include/string/stdstring.h @@ -47,6 +47,15 @@ char *string_ucwords(char* s); char *string_replace_substring(const char *in, const char *pattern, const char *by); +/* Remove leading whitespaces */ +char *string_trim_whitespace_left(char *const s); + +/* Remove trailing whitespaces */ +char *string_trim_whitespace_right(char *const s); + +/* Remove leading and trailing whitespaces */ +char *string_trim_whitespace(char *const s); + RETRO_END_DECLS #endif diff --git a/libretro-common/string/stdstring.c b/libretro-common/string/stdstring.c index 64a50d6f67..c114f1ed16 100644 --- a/libretro-common/string/stdstring.c +++ b/libretro-common/string/stdstring.c @@ -118,3 +118,52 @@ char *string_replace_substring(const char *in, return out; } + +/* Non-GPL licensed versions of whitespace trimming: + * http://stackoverflow.com/questions/656542/trim-a-string-in-c + */ + +/* Remove leading whitespaces */ +char *string_trim_whitespace_left(char *const s) +{ + if(s && *s) + { + size_t len = strlen(s); + char *cur = s; + + while(*cur && isspace(*cur)) + ++cur, --len; + + if(s != cur) + memmove(s, cur, len + 1); + + } + + return s; +} + +/* Remove trailing whitespaces */ +char *string_trim_whitespace_right(char *const s) +{ + if(s && *s) + { + size_t len = strlen(s); + char *cur = s + len - 1; + + while(cur != s && isspace(*cur)) + --cur, --len; + + cur[isspace(*cur) ? 0 : 1] = '\0'; + } + + return s; +} + +/* Remove leading and trailing whitespaces */ +char *string_trim_whitespace(char *const s) +{ + string_trim_whitespace_right(s); /* order matters */ + string_trim_whitespace_left(s); + + return s; +}