How do I trim leading/trailing whitespace in a standard way?

后端 未结 30 2418
一个人的身影
一个人的身影 2020-11-22 02:06

Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I\'d roll my own, but I would think this is a common problem wit

30条回答
  •  Happy的楠姐
    2020-11-22 02:27

    This one is short and simple, uses for-loops and doesn't overwrite the string boundaries. You can replace the test with isspace() if needed.

    void trim (char *s)         // trim leading and trailing spaces+tabs
    {
     int i,j,k, len;
    
     j=k=0;
     len = strlen(s);
                        // find start of string
     for (i=0; i=j; i--) if ((s[i]!=32) && (s[i]!=9)) { k=i+1; break;} 
    
     if (k<=j) {s[0]=0; return;}        // all whitespace (j==k==0)
    
     len=k-j;
     for (i=0; i

提交回复
热议问题