From d0cbec4a197a7bfa6fe60bb7829f978697b49520 Mon Sep 17 00:00:00 2001 From: Daniel Verkamp Date: Thu, 28 Apr 2016 16:41:45 -0700 Subject: [PATCH] lib/util: add spdk_str_trim() Function to trim leading and trailing whitespace from a string. Originally based on code imported from istgt. Change-Id: I87abe584130bdf4930098fadb8e57291f18eda7f Signed-off-by: Daniel Verkamp --- include/spdk/string.h | 7 +++++++ lib/util/string.c | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/include/spdk/string.h b/include/spdk/string.h index 67512ba34..ffcc8a96c 100644 --- a/include/spdk/string.h +++ b/include/spdk/string.h @@ -67,6 +67,13 @@ char *spdk_strlwr(char *s); */ char *spdk_strsepq(char **stringp, const char *delim); +/** + * Trim whitespace from a string in place. + * + * \param s String to trim. + */ +char *spdk_str_trim(char *s); + #ifdef __cplusplus } #endif diff --git a/lib/util/string.c b/lib/util/string.c index 5355ffa2e..8aee731b3 100644 --- a/lib/util/string.c +++ b/lib/util/string.c @@ -166,3 +166,37 @@ spdk_strsepq(char **stringp, const char *delim) return p; } + +char * +spdk_str_trim(char *s) +{ + char *p, *q; + + if (s == NULL) { + return NULL; + } + + /* remove header */ + p = s; + while (*p != '\0' && isspace(*p)) { + p++; + } + + /* remove tailer */ + q = p + strlen(p); + while (q - 1 >= p && isspace(*(q - 1))) { + q--; + *q = '\0'; + } + + /* if remove header, move */ + if (p != s) { + q = s; + while (*p != '\0') { + *q++ = *p++; + } + *q = '\0'; + } + + return s; +}