Skip to content

Instantly share code, notes, and snippets.

@kisom
Created September 19, 2011 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kisom/1226313 to your computer and use it in GitHub Desktop.
Save kisom/1226313 to your computer and use it in GitHub Desktop.
C function to strip leading and trailing whitespace from a line of text
/*
* written by kyle isom <coder@kyleisom.net>
* license: isc / public domain dual license
* one of the functions i wrote for the lurker project
* (https://github.com/kisom/lurker)
*
* C function to strip leading and trailing whitespace
* from a string
* added as a gist because I am not near a compiler or editor and want to commit
* my notes to memory
*/
/*
* Internal function to strip the leading and trailing whitespace off a line
* of text.
* arguments:
* - buffer: a line of text. in lurker, this is already guaranteed
* to be an allocated buffer with a line of text in it, and it is
* guaranteed not to have any newlines or carriage returns. if it
* is used elsewhere, the checks may need to be tweaked.
* returns:
* - NULL on function failure (i.e. malloc error, NULL string passed
* in, empty string passed in)
* - char * pointer to a string containing the stripped string
* IMPORTANT: this will need to be freed by the caller.
*/
char
*strip(char *buf)
{
size_t start, end;
char *l_start, *l_end, *stripped;
size_t buf_sz, strip_sz;
short int found_start, found_end;
buf_sz = 0;
strip_sz = 0;
found_start = 0; /* set to 1 to stop searching */
found_end = 0;
start = 0;
/*
* Ensure we aren't dealing with a single char or unallocated
* buffer.
*/
if ((NULL == buf) || ('\0' == buf[0]))
return NULL;
/* Figure out the size of the buffer. */
while ('\0' != buf[++buf_sz]) { }
end = strlen(buf);
/*
* Stop conditions: the pointers meet and haven't found the
* first and last non-whitespace characters.
*/
while ((start < end) && !(found_start && found_end)) {
if (!found_start)
switch (buf[start]) {
case ' ':
case '\t':
start++;
break;
default:
found_start = 1;
break;
}
if (!found_end)
switch (buf[end]) {
case ' ':
case '\t':
case '\0':
end--;
break;
default:
end++;
found_end = 1;
break;
}
}
strip_sz = end - start;
if (0 == strip_sz)
return NULL;
stripped = calloc(strip_sz + 1, sizeof(char));
if (NULL == stripped)
return NULL;
snprintf(stripped, strip_sz + 1, "%s", buf + start);
return stripped;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment