Advertisement
wermington

Trim

May 18th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.06 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. char * trim(const char *str)
  7. {
  8.   if(str == NULL)
  9.     return NULL;
  10.  
  11.   // Trim leading space
  12.   while(isspace(*str)) str++;
  13.  
  14.   if(*str == 0)  // If string is "empty" - contains only whitespaces -- return null
  15.   {
  16.     return NULL;
  17.   }
  18.  
  19.   // Trim trailing space
  20.   const char * end = str + strlen(str) - 1; // go to end of string
  21.   while(end > str && isspace(*end)) end--; // go to first nonspace char
  22.   end;
  23.  
  24.   // Set output size to minimum of trimmed string length and buffer size minus 1
  25.   size_t out_size = (end - str) + 1; // Do not forget to 0
  26.   char *out = malloc(out_size * sizeof(char));
  27.  
  28.   // Copy trimmed string and add null terminator
  29.   memcpy(out, str, out_size);
  30.   out[out_size] = 0;
  31.  
  32.   return out;
  33. }
  34.  
  35.  
  36. int main(void)
  37. {
  38.     const char * str = "   \t\t   AHOJ SVET \t\t     ";
  39.     printf("String without trim: \"%s\"\n", str);
  40.     char *trimmed = trim(str);
  41.     printf("Trimmed string: \"%s\"\n", trimmed);
  42.     free(trimmed);
  43.  
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement