c - How do I trim leading/trailing whitespace in a standard way?

ID : 20021

viewed : 20

Tags : cstringwhitespacetrimc

Top 5 Answer for c - How do I trim leading/trailing whitespace in a standard way?

vote vote

95

If you can modify the string:

// Note: This function returns a pointer to a substring of the original string. // If the given string was allocated dynamically, the caller must not overwrite // that pointer with the returned value, since the original pointer must be // deallocated using the same allocator with which it was allocated.  The return // value must NOT be deallocated using free() etc. char *trimwhitespace(char *str) {   char *end;    // Trim leading space   while(isspace((unsigned char)*str)) str++;    if(*str == 0)  // All spaces?     return str;    // Trim trailing space   end = str + strlen(str) - 1;   while(end > str && isspace((unsigned char)*end)) end--;    // Write new null terminator character   end[1] = '\0';    return str; } 

If you can't modify the string, then you can use basically the same method:

// Stores the trimmed input string into the given output buffer, which must be // large enough to store the result.  If it is too small, the output is // truncated. size_t trimwhitespace(char *out, size_t len, const char *str) {   if(len == 0)     return 0;    const char *end;   size_t out_size;    // Trim leading space   while(isspace((unsigned char)*str)) str++;    if(*str == 0)  // All spaces?   {     *out = 0;     return 1;   }    // Trim trailing space   end = str + strlen(str) - 1;   while(end > str && isspace((unsigned char)*end)) end--;   end++;    // Set output size to minimum of trimmed string length and buffer size minus 1   out_size = (end - str) < len-1 ? (end - str) : len-1;    // Copy trimmed string and add null terminator   memcpy(out, str, out_size);   out[out_size] = 0;    return out_size; } 
vote vote

90

Here's one that shifts the string into the first position of your buffer. You might want this behavior so that if you dynamically allocated the string, you can still free it on the same pointer that trim() returns:

char *trim(char *str) {     size_t len = 0;     char *frontp = str;     char *endp = NULL;      if( str == NULL ) { return NULL; }     if( str[0] == '\0' ) { return str; }      len = strlen(str);     endp = str + len;      /* Move the front and back pointers to address the first non-whitespace      * characters from each end.      */     while( isspace((unsigned char) *frontp) ) { ++frontp; }     if( endp != frontp )     {         while( isspace((unsigned char) *(--endp)) && endp != frontp ) {}     }      if( frontp != str && endp == frontp )             *str = '\0';     else if( str + len - 1 != endp )             *(endp + 1) = '\0';      /* Shift the string so that it starts at str so that if it's dynamically      * allocated, we can still free it on the returned pointer.  Note the reuse      * of endp to mean the front of the string buffer now.      */     endp = str;     if( frontp != str )     {             while( *frontp ) { *endp++ = *frontp++; }             *endp = '\0';     }      return str; } 

Test for correctness:

#include <stdio.h> #include <string.h> #include <ctype.h>  /* Paste function from above here. */  int main() {     /* The test prints the following:     [nothing to trim] -> [nothing to trim]     [    trim the front] -> [trim the front]     [trim the back     ] -> [trim the back]     [    trim front and back     ] -> [trim front and back]     [ trim one char front and back ] -> [trim one char front and back]     [ trim one char front] -> [trim one char front]     [trim one char back ] -> [trim one char back]     [                   ] -> []     [ ] -> []     [a] -> [a]     [] -> []     */      char *sample_strings[] =     {             "nothing to trim",             "    trim the front",             "trim the back     ",             "    trim front and back     ",             " trim one char front and back ",             " trim one char front",             "trim one char back ",             "                   ",             " ",             "a",             "",             NULL     };     char test_buffer[64];     char comparison_buffer[64];     size_t index, compare_pos;      for( index = 0; sample_strings[index] != NULL; ++index )     {         // Fill buffer with known value to verify we do not write past the end of the string.         memset( test_buffer, 0xCC, sizeof(test_buffer) );         strcpy( test_buffer, sample_strings[index] );         memcpy( comparison_buffer, test_buffer, sizeof(comparison_buffer));          printf("[%s] -> [%s]\n", sample_strings[index],                                  trim(test_buffer));          for( compare_pos = strlen(comparison_buffer);              compare_pos < sizeof(comparison_buffer);              ++compare_pos )         {             if( test_buffer[compare_pos] != comparison_buffer[compare_pos] )             {                 printf("Unexpected change to buffer @ index %u: %02x (expected %02x)\n",                     compare_pos, (unsigned char) test_buffer[compare_pos], (unsigned char) comparison_buffer[compare_pos]);             }         }     }      return 0; } 

Source file was trim.c. Compiled with 'cc -Wall trim.c -o trim'.

vote vote

74

My solution. String must be changeable. The advantage above some of the other solutions that it moves the non-space part to the beginning so you can keep using the old pointer, in case you have to free() it later.

void trim(char * s) {     char * p = s;     int l = strlen(p);      while(isspace(p[l - 1])) p[--l] = 0;     while(* p && isspace(* p)) ++p, --l;      memmove(s, p, l + 1); }    

This version creates a copy of the string with strndup() instead of editing it in place. strndup() requires _GNU_SOURCE, so maybe you need to make your own strndup() with malloc() and strncpy().

char * trim(char * s) {     int l = strlen(s);      while(isspace(s[l - 1])) --l;     while(* s && isspace(* s)) ++s, --l;      return strndup(s, l); } 
vote vote

69

Here's my C mini library for trimming left, right, both, all, in place and separate, and trimming a set of specified characters (or white space by default).

contents of strlib.h:

#ifndef STRLIB_H_ #define STRLIB_H_ 1 enum strtrim_mode_t {     STRLIB_MODE_ALL       = 0,      STRLIB_MODE_RIGHT     = 0x01,      STRLIB_MODE_LEFT      = 0x02,      STRLIB_MODE_BOTH      = 0x03 };  char *strcpytrim(char *d, // destination                  char *s, // source                  int mode,                  char *delim                  );  char *strtriml(char *d, char *s); char *strtrimr(char *d, char *s); char *strtrim(char *d, char *s);  char *strkill(char *d, char *s);  char *triml(char *s); char *trimr(char *s); char *trim(char *s); char *kill(char *s); #endif 

contents of strlib.c:

#include <strlib.h>  char *strcpytrim(char *d, // destination                  char *s, // source                  int mode,                  char *delim                  ) {     char *o = d; // save orig     char *e = 0; // end space ptr.     char dtab[256] = {0};     if (!s || !d) return 0;      if (!delim) delim = " \t\n\f";     while (*delim)          dtab[*delim++] = 1;      while ( (*d = *s++) != 0 ) {          if (!dtab[0xFF & (unsigned int)*d]) { // Not a match char             e = 0;       // Reset end pointer         } else {             if (!e) e = d;  // Found first match.              if ( mode == STRLIB_MODE_ALL || ((mode != STRLIB_MODE_RIGHT) && (d == o)) )                  continue;         }         d++;     }     if (mode != STRLIB_MODE_LEFT && e) { // for everything but trim_left, delete trailing matches.         *e = 0;     }     return o; }  // perhaps these could be inlined in strlib.h char *strtriml(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_LEFT, 0); } char *strtrimr(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_RIGHT, 0); } char *strtrim(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_BOTH, 0); } char *strkill(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_ALL, 0); }  char *triml(char *s) { return strcpytrim(s, s, STRLIB_MODE_LEFT, 0); } char *trimr(char *s) { return strcpytrim(s, s, STRLIB_MODE_RIGHT, 0); } char *trim(char *s) { return strcpytrim(s, s, STRLIB_MODE_BOTH, 0); } char *kill(char *s) { return strcpytrim(s, s, STRLIB_MODE_ALL, 0); } 

The one main routine does it all. It trims in place if src == dst, otherwise, it works like the strcpy routines. It trims a set of characters specified in the string delim, or white space if null. It trims left, right, both, and all (like tr). There is not much to it, and it iterates over the string only once. Some folks might complain that trim right starts on the left, however, no strlen is needed which starts on the left anyway. (One way or another you have to get to the end of the string for right trims, so you might as well do the work as you go.) There may be arguments to be made about pipelining and cache sizes and such -- who knows. Since the solution works from left to right and iterates only once, it can be expanded to work on streams as well. Limitations: it does not work on unicode strings.

vote vote

50

Here is my attempt at a simple, yet correct in-place trim function.

void trim(char *str) {     int i;     int begin = 0;     int end = strlen(str) - 1;      while (isspace((unsigned char) str[begin]))         begin++;      while ((end >= begin) && isspace((unsigned char) str[end]))         end--;      // Shift all characters back to the start of the string array.     for (i = begin; i <= end; i++)         str[i - begin] = str[i];      str[i - begin] = '\0'; // Null terminate string. } 

Top 3 video Explaining c - How do I trim leading/trailing whitespace in a standard way?

Related QUESTION?