Skip to content

Commit

Permalink
string_utils: add trim_both
Browse files Browse the repository at this point in the history
trim_both removes whitespaces from both side of a string.

Signed-off-by: Yuxuan Shui <[email protected]>
  • Loading branch information
yshui committed Jul 17, 2022
1 parent e757a64 commit 7e83374
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
28 changes: 28 additions & 0 deletions src/string_utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
1 change: 1 addition & 0 deletions src/string_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 **);
Expand Down
2 changes: 1 addition & 1 deletion subprojects/test.h/test.h
Original file line number Diff line number Diff line change
Expand Up @@ -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; \
} \
Expand Down

0 comments on commit 7e83374

Please sign in to comment.