OneBite.Dev - Coding blog in a bite size

trim a string in C

Code snippet on how to trim a string in C

  char *trim(char *s){
      int i = strlen(s) - 1;
      while (isspace(s[i]) && i >= 0)
          i--;
      s[i + 1] = '\0';
      while (isspace(s[0]))
          s++;
      return s;
  }

The purpose of this code is to trim whitespace from the beginning and end of a string in the C programming language. It takes the string to be trimmed as an argument (in this case ‘s’) and returns the trimmed string. The code begins by setting a variable ‘i’ to the length of the string minus one. Then a loop is used to cycle through the string from the end, counting backwards. The loop will stop when the character at position ‘i’ is not a whitespace character, or when ‘i’ is less than zero (the start of the string). After the loop ends, the character at position ‘i+1’ is set to ‘\0’ which marks the end of the string. Then a loop is used to cycle through the string from the start, until a non-whitespace character is reached. Then the function returns the string pointer at this position, which is the trimmed string.

c