Next: strcat() Up: Idiomatic C Previous: Walking a linked

Remove trailing spaces

   int trim(char s[])
   /* remove trailing spaces from string s */
   int n;

   for (n= strlen(s) - 1;  n >= 0;  n--)
      if (s[n] != ' ')  break;

   s[n + 1]= '\0';

   return n;
}

Note: strlen(s) - 1 to allow for the null on the end.

Note: counting down is natural to the problem.

Note: use of break to terminate the for loop permaturely.

Note: opportunity taken to return information about the trimmed size.

Note: the for loop catches extreme case (all spaces).



Next: strcat() Up: Idiomatic C Previous: Walking a linked


maspjw@
Tue Sep 27 15:29:34 BST 1994