Posted By

mwb1100 on 03/16/10


Tagged

trim domain public LTrim RTrim


Versions (?)

string trim functions


 / Published in: C
 

  1. #include <ctype.h>
  2. #include <string.h>
  3.  
  4. /*
  5.   Public domain implementations of in-place string trim functions
  6.  
  7.   Michael Burr
  8.   2010
  9. */
  10.  
  11. char* ltrim(char* s)
  12. {
  13. char* newstart = s;
  14.  
  15. while (isspace( *newstart)) {
  16. ++newstart;
  17. }
  18.  
  19. // newstart points to first non-whitespace char (which might be '\0')
  20. memmove( s, newstart, strlen( newstart) + 1); // don't forget to move the '\0' terminator
  21.  
  22. return s;
  23. }
  24.  
  25.  
  26. char* rtrim( char* s)
  27. {
  28. char* end = s + strlen( s);
  29.  
  30. // find the last non-whitespace character
  31. while ((end != s) && isspace( *(end-1))) {
  32. --end;
  33. }
  34.  
  35. // at this point either (end == s) and s is either empty or all whitespace
  36. // so it needs to be made empty, or
  37. // end points just past the last non-whitespace character (it might point
  38. // at the '\0' terminator, in which case there's no problem writing
  39. // another there).
  40. *end = '\0';
  41.  
  42. return s;
  43. }
  44.  
  45. char* trim( char* s)
  46. {
  47. return rtrim( ltrim( s));
  48. }

Report this snippet  

You need to login to post a comment.