I wrote C code to implement this function. I also wrote some trivial tests to make sure my function does reasonable things.
This function writes to the buffer that you provide, and should never be written to the end of the buffer, so it should not be prone to buffer overflow problems.
Note: only Test () uses stdio.h, so if you just need a function, you need to include ctype.h (for isspace ()) and string.h (for strlen ()).
// strstrip.c -- implement white space stripping for a string in C // // This code is released into the public domain. // // You may use it for any purpose whatsoever, and you don't need to advertise // where you got it, but you aren't allowed to sue me for giving you free // code; all the risk of using this is yours. #include <ctype.h> #include <stdio.h> #include <string.h> // strstrip() -- strip leading and trailing white space from a string // // Copies from sIn to sOut, writing at most lenOut characters. // // Returns number of characters in returned string, or -1 on an error. // If you get -1 back, then nothing was written to sOut at all. int strstrip(char *sOut, unsigned int lenOut, char const *sIn) { char const *pStart, *pEnd; unsigned int len; char *pOut; // if there is no room for any output, or a null pointer, return error! if (0 == lenOut || !sIn || !sOut) return -1; pStart = sIn; pEnd = sIn + strlen(sIn) - 1; // skip any leading whitespace while (*pStart && isspace(*pStart)) ++pStart; // skip any trailing whitespace while (pEnd >= sIn && isspace(*pEnd)) --pEnd; pOut = sOut; len = 0; // copy into output buffer while (pStart <= pEnd && len < lenOut - 1) { *pOut++ = *pStart++; ++len; } // ensure output buffer is properly terminated *pOut = '\0'; return len; } void Test(const char *s) { int len; char buf[1024]; len = strstrip(buf, sizeof(buf), s); if (!s) s = "**null**"; // don't ask printf to print a null string if (-1 == len) *buf = '\0'; // don't ask printf to print garbage from buf printf("Input: \"%s\" Result: \"%s\" (%d chars)\n", s, buf, len); } main() { Test(NULL); Test(""); Test(" "); Test(" "); Test("x"); Test(" x"); Test(" x "); Test(" xyz "); Test("xyz"); }
source share