Last active
December 16, 2015 20:09
-
-
Save RhysU/5490133 to your computer and use it in GitHub Desktop.
Solution for http://stackoverflow.com/questions/122616/painless-way-to-trim-leading-trailing-whitespace-in-c/4505533#4505533 also appearing at http://agentzlerich.blogspot.com/2011/01/c-header-only-unit-testing-with-fctx.html
This file contains 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
#include <ctype.h> | |
void trim(char * const a) | |
{ | |
char *p = a, *q = a; | |
while (isspace(*q)) ++q; | |
while (*q) *p++ = *q++; | |
*p = '\0'; | |
while (p > a && isspace(*--p)) *p = '\0'; | |
} | |
/* See http://fctx.wildbearsoftware.com/ */ | |
#include "fct.h" | |
FCT_BGN() | |
{ | |
FCT_QTEST_BGN(trim) | |
{ | |
{ char s[] = ""; trim(s); fct_chk_eq_str("", s); } // Trivial | |
{ char s[] = " "; trim(s); fct_chk_eq_str("", s); } // Trivial | |
{ char s[] = "\t"; trim(s); fct_chk_eq_str("", s); } // Trivial | |
{ char s[] = "a"; trim(s); fct_chk_eq_str("a", s); } // NOP | |
{ char s[] = "abc"; trim(s); fct_chk_eq_str("abc", s); } // NOP | |
{ char s[] = " a"; trim(s); fct_chk_eq_str("a", s); } // Leading | |
{ char s[] = " a c"; trim(s); fct_chk_eq_str("a c", s); } // Leading | |
{ char s[] = "a "; trim(s); fct_chk_eq_str("a", s); } // Trailing | |
{ char s[] = "a c "; trim(s); fct_chk_eq_str("a c", s); } // Trailing | |
{ char s[] = " a "; trim(s); fct_chk_eq_str("a", s); } // Both | |
{ char s[] = " a c "; trim(s); fct_chk_eq_str("a c", s); } // Both | |
// Villemoes pointed out an edge case that corrupted memory. Thank you. | |
// http://stackoverflow.com/questions/122616/#comment23332594_4505533 | |
{ | |
char s[] = "a "; // Buffer with whitespace before s + 2 | |
trim(s + 2); // Trim " " containing only whitespace | |
fct_chk_eq_str("", s + 2); // Ensure correct result from the trim | |
fct_chk_eq_str("a ", s); // Ensure preceding buffer not mutated | |
} | |
} | |
FCT_QTEST_END(); | |
} | |
FCT_END(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment