直接贴源码吧,主要是备查。

file: trim.c

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>

  5. #ifndef SUCCESS
  6. #define SUCCESS 1
  7. #endif

  8. /* TRIM LEFT */

  9. int rtrim( char *pszString)
  10. {
  11.     int nForwardCursor = 0;
  12.     int nTrailingCursor = 0;
  13.     int bTrim = 1;

  14.     for( nForwardCursor = 0 ; pszString[nForwardCursor] != '\0'; nForwardCursor++ )
  15.         if ( bTrim && isspace( pszString[nForwardCursor] ))
  16.             continue ;
  17.         else {
  18.             bTrim = 0;
  19.             pszString[nTrailingCursor] = pszString[nForwardCursor];
  20.             nTrailingCursor++;
  21.         }
  22.     pszString[nTrailingCursor] = '\0';
  23.     return SUCCESS;
  24. }

  25. /* TRIM RIGHT */
  26. int ltrim( char *pszString )
  27. {
  28.     int nForwardCursor = 0;
  29.     int nTrailingCursor = 0;
  30.     int bTrim = 1;
  31.     for ( nForwardCursor=strlen(pszString)-1;
  32.             nForwardCursor >= 0 && isspace( pszString[nForwardCursor] );
  33.             nForwardCursor-- )
  34.     {
  35.     }
  36.     pszString[nForwardCursor+1] = '\0';
  37.     return SUCCESS;
  38. }

  39. /* TRIM LEFT & RIGHT */
  40. int trim(char *str)
  41. {
  42.     ltrim(str);
  43.     rtrim(str);
  44.     return SUCCESS;
  45. }
测试代码如下:
file: test.c

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>

  5. int main( void )
  6. {
  7.     char    s[80];
  8.     sprintf(s,"%s"," aaaaaa ");
  9.     printf("=== strlen = %d === \n",strlen(s));
  10.     trim(s);
  11.     printf("=== len = %d ===\n",strlen(s));
  12.     return 0;
  13. }
编译:
cc -o test test.c trim.c

运行:
$ ./test



11-10 15:53