How do I remove empty characters from both sides of a string in C

  • 2020-04-02 00:56:19
  • OfStack

Today in a foreign website, see the following code, feel quite streamlined.

char *tr ( char *s )
{
  int i = 0;
  int j = strlen ( s ) - 1;
  int k = 0;

  while ( isspace ( s[i] ) && s[i] != '0' )
    i++;

  while ( isspace ( s[j] ) && j >= 0 )
    j--;

  while ( i <= j )
    s[k++] = s[i++];

  s[k] = '0';

  return s;
}

Related articles: