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

Report this snippet  

You need to login to post a comment.