diff th_string.c @ 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 f6e0a32b5906
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)