/*
   trim - Functions to erase invisible characters in strings
   Copyright (C) 2002 John Ericson
*/

#include "trim.h"


/* Returns a copy of string without
 * leading and trailing blank characters (space, tab & newline)
 */
char *trim(char *str) {

   str = ltrim(str);
   str = rtrim(str);

   return(str);
}

/* Returns a copy of a string without
 * leading blank characters (space, tab & newline)
 */
char *ltrim(char *str) {

   /* I think this is probably the most efficient way */
   strrev(str);
   rtrim(str);
   strrev(str);

   return(str);
}

/* Returns a copy of a string without
 * trailing blank characters (space, tab & newline)
 */
char *rtrim(char *str) {

   int l = strlen(str) - 1;

   while (l >= 0)
      if (str[l] != ' ' &&
         str[l] != '\n' &&
         str[l] != '\t')
      {
         str[l + 1] = 0;
         break;
      } else
         l--;

   if ((l < 0) && (
      str[0] == ' ' ||
      str[0] == '\n' ||
      str[0] == '\t'))
   {
      str[0] = '\0';
   }

   return(str);
}