Last active
November 12, 2017 08:39
-
-
Save jdmichaud/731835d32282583c1f68ebe9a3fdd44f to your computer and use it in GitHub Desktop.
simple trim function in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cc -Wall -Wextra -Wpedantic -Wfatal-errors -O3 /tmp/trim.c -o /tmp/trim | |
#include <stdio.h> | |
#include <ctype.h> | |
#include <string.h> | |
#include <stdint.h> | |
#define FAIL() { \ | |
++totalres; \ | |
fprintf(stderr, "%s failed at %s(%i)\n", __func__, __FILE__, __LINE__); \ | |
} | |
/** | |
* trim the string s of leading and trailing whitespaces | |
* \params s the string to trim | |
* \params output optional pointer to which the result is copied | |
* \returns a pointer to the result | |
* if output is NULL, the result is copied in s and s is returned. | |
* if output is not NULL, the result is copied in output and output is returned. | |
*/ | |
char *trim(char *s, char *output) { | |
if (*s == 0) return s; | |
char *beg = s; | |
char *end = s; | |
while (*beg && isspace(*beg)) ++beg; | |
while (*end) ++end; | |
while ((end - 1) > beg && isspace(*(end - 1))) --end; | |
if (output != NULL) s = output; | |
memmove(s, beg, end - beg + 1); | |
s[end - beg] = 0; | |
return s; | |
} | |
int main() { | |
char test[255]; | |
uint8_t totalres = 0; | |
if (strcmp("toto", trim(" toto ", test))) FAIL(); | |
if (strcmp("tot o", trim(" tot o", test))) FAIL(); | |
if (strcmp("tot o", trim(" tot o ", test))) FAIL(); | |
if (strcmp("toto", trim("toto", test))) FAIL(); | |
if (strcmp("o", trim("o ", test))) FAIL(); | |
if (strcmp("o", trim(" o", test))) FAIL(); | |
if (strcmp("", trim("", test))) FAIL(); | |
if (strcmp("", trim(" ", test))) FAIL(); | |
if (strcmp("", trim(" ", test))) FAIL(); | |
memcpy(test, " toto ", strnlen(" toto ", 255)); | |
test[strnlen(" toto ", 255)] = 0; | |
if (strcmp("toto", trim(test, NULL))) FAIL(); | |
return totalres; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment