diff --git a/lib/cstr.c b/lib/cstr.c new file mode 100644 index 0000000..8dd024b --- /dev/null +++ b/lib/cstr.c @@ -0,0 +1,62 @@ +#include "cstr.h" +#include +#include + +/** + * trim whitespace of a cstring (both beginning and end). a null terminator + * will be placed after the last non-whitespace character. this modifies the + * string. + * + * @param str: the string to trim + * + * @return a pointer to the beginning of the trimmed string. the string is not + * copied, and the returned pointer points to somewhere within the + * original string. + */ +char * +strtrim (char *str) +{ + strtrimr (str); + return strtriml (str); +} + +/** + * trim whitespace of a cstring on the left (beginning of string). the original + * string will be preserved. + * + * @param str: the string to trim + * + * @return a pointer to the beginning of the trimmed string. the string is not + * copied, and the returned pointer points to somewhere within the + * original string. + */ +char * +strtriml (const char *str) +{ + while (*str && isspace (*str)) + str++; + + return str; +} + +/** + * trim whitespace of a cstring on the right (end of string). a null terminator + * will be placed after the last non-whitespace character. this modifies the + * string. + * + * @param str: the string to trim + * + * @return the new string length + */ +size_t +strtrimr (char *str) +{ + size_t len, i; + + i = len = strlen (str); + while (i <= len && isspace (str[i - 1])) + i--; + str[i] = '\0'; + + return i; +} diff --git a/lib/inc/cstr.h b/lib/inc/cstr.h new file mode 100644 index 0000000..f4f9639 --- /dev/null +++ b/lib/inc/cstr.h @@ -0,0 +1,10 @@ +#ifndef CUTILS_CSTR_H_ +#define CUTILS_CSTR_H_ + +#include + +char *strtrim (char *str); /* trim whitespace of a cstring (both beginning and end) */ +char *strtriml (const char *str); /* trim whitespace of a cstring on the left (beginning of string). */ +size_t strtrimr (char *str); /* trim whitespace of a cstring on the right (end of string) */ + +#endif // CUTILS_CSTR_H_ diff --git a/test/main.c b/test/main.c index 2b210c5..09da880 100644 --- a/test/main.c +++ b/test/main.c @@ -1,6 +1,9 @@ +#include #include #include +#include +#include "cstr.h" #define CUTILS_DEBUG_TRACE #include "debug.h" #include "log.h" @@ -9,6 +12,7 @@ int main (void) { char *ptr; + size_t len; ptr = malloc ((sizeof *ptr) * 1); ptr = realloc (ptr, (sizeof *ptr) * 4096); @@ -22,5 +26,18 @@ main (void) log_print (LOG_LEVEL_DEBUG, "debug! %04.04f\n", 13.37); log_print_fl (LOG_LEVEL_OK, __FILE__, __LINE__, "file and line\n"); + char s[] = " Hello, World!\n "; + len = strtrimr (s); + assert (len == 17); + assert (strlen (s) == 17); + char *sn = strtriml (s); + assert (sn == s + 4); + assert (strlen (sn) == 13); + char s2[] = " Hello, World!\n "; + sn = strtrim (s2); + assert (strlen (s2) == 17); + assert (sn == s2 + 4); + assert (strlen (sn) == 13); + return EXIT_SUCCESS; }