Mercurial > hg > th-libs
changeset 90:2b1f7f1ca8e4
Add new function th_strdup_trim().
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Tue, 20 May 2014 04:27:30 +0300 |
parents | 30690f5c4cae |
children | eca8ffe4e260 |
files | th_string.c th_string.h |
diffstat | 2 files changed, 39 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/th_string.c Sat May 17 22:39:37 2014 +0300 +++ b/th_string.c Tue May 20 04:27:30 2014 +0300 @@ -49,6 +49,36 @@ } +/* Like strdup, but trims whitespace from stringImplementation of strdup() with a NULL check + */ +char *th_strdup_trim(const char *s, const int flags) +{ + char *res; + size_t start, end, len; + if (s == NULL) + return NULL; + + len = strlen(s); + if (flags & TH_TRIM_START) + for (start = 0; start < len && th_isspace(s[start]); start++); + else + start = 0; + + if (flags & TH_TRIM_END) + for (end = len; end > start && th_isspace(s[end]); end--); + else + end = len; + + len = end - start + 1; + if ((res = th_malloc(len + 1)) == NULL) + return NULL; + + memcpy(res, s, len); + res[len] = 0; + return res; +} + + /* Simulate a sprintf() that allocates memory */ char *th_strdup_vprintf(const char *fmt, va_list args)
--- a/th_string.h Sat May 17 22:39:37 2014 +0300 +++ b/th_string.h Tue May 20 04:27:30 2014 +0300 @@ -40,10 +40,19 @@ #define th_toupper(c) toupper((int)(unsigned char) c) +enum +{ + TH_TRIM_START = 1, + TH_TRIM_END = 2, + TH_TRIM_BOTH = 3 +}; + + /* Normal NUL-terminated string functions */ char *th_strdup(const char *); char *th_strndup(const char *, const size_t); +char *th_strdup_trim(const char *, const int); int th_strcasecmp(const char *, const char *); int th_strncasecmp(const char *, const char *, size_t);