From 7e833744b7083f530afb25f287c929f7edad6701 Mon Sep 17 00:00:00 2001 From: Yuxuan Shui Date: Sun, 17 Jul 2022 15:30:42 +0100 Subject: [PATCH] string_utils: add trim_both trim_both removes whitespaces from both side of a string. Signed-off-by: Yuxuan Shui --- src/string_utils.c | 28 ++++++++++++++++++++++++++++ src/string_utils.h | 1 + subprojects/test.h/test.h | 2 +- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/string_utils.c b/src/string_utils.c index 65af0f20..ee5bb2da 100644 --- a/src/string_utils.c +++ b/src/string_utils.c @@ -127,3 +127,31 @@ TEST_CASE(strtod_simple) { TEST_EQUAL(result, 0.5); TEST_EQUAL(*end, '\0'); } + +const char *trim_both(const char *src, size_t *length) { + size_t i = 0; + while (isspace(src[i])) { + i++; + } + size_t j = strlen(src) - 1; + while (j > i && isspace(src[j])) { + j--; + } + *length = j - i + 1; + return src + i; +} + +TEST_CASE(trim_both) { + size_t length; + const char *str = trim_both(" \t\n\r\f", &length); + TEST_EQUAL(length, 0); + TEST_EQUAL(*str, '\0'); + + str = trim_both(" asdfas ", &length); + TEST_EQUAL(length, 6); + TEST_STRNEQUAL(str, "asdfas", length); + + str = trim_both(" asdf asdf ", &length); + TEST_EQUAL(length, 9); + TEST_STRNEQUAL(str, "asdf asdf", length); +} diff --git a/src/string_utils.h b/src/string_utils.h index 38febde6..461173a3 100644 --- a/src/string_utils.h +++ b/src/string_utils.h @@ -11,6 +11,7 @@ char *mstrjoin(const char *src1, const char *src2); char *mstrjoin3(const char *src1, const char *src2, const char *src3); void mstrextend(char **psrc1, const char *src2); +const char *trim_both(const char *src, size_t *length); /// Parse a floating point number of form (+|-)?[0-9]*(\.[0-9]*) double strtod_simple(const char *, const char **); diff --git a/subprojects/test.h/test.h b/subprojects/test.h/test.h index d2ec6bf6..71522e13 100644 --- a/subprojects/test.h/test.h +++ b/subprojects/test.h/test.h @@ -84,7 +84,7 @@ struct test_file_metadata __attribute__((weak)) * test_file_head; const char *part2 = " != " #b; \ size_t len2 = len + strlen(part2) + 3; \ char *buf = malloc(len2); \ - snprintf(buf, len2, "\"%.*s\"%s", len, a, part2); \ + snprintf(buf, len2, "\"%.*s\"%s", (int)len, a, part2); \ SET_FAILURE(buf, true); \ return; \ } \