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

后端 未结 30 2383
一个人的身影
一个人的身影 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条回答
  •  春和景丽
    2020-11-22 02:25

    To trim my strings from the both sides I use the oldie but the gooody ;) It can trim anything with ascii less than a space, meaning that the control chars will be trimmed also !

    char *trimAll(char *strData)
    {
      unsigned int L = strlen(strData);
      if(L > 0){ L--; }else{ return strData; }
      size_t S = 0, E = L;
      while((!(strData[S] > ' ') || !(strData[E] > ' ')) && (S >= 0) && (S <= L) && (E >= 0) && (E <= L))
      {
        if(strData[S] <= ' '){ S++; }
        if(strData[E] <= ' '){ E--; }
      }
      if(S == 0 && E == L){ return strData; } // Nothing to be done
      if((S >= 0) && (S <= L) && (E >= 0) && (E <= L)){
        L = E - S + 1;
        memmove(strData,&strData[S],L); strData[L] = '\0';
      }else{ strData[0] = '\0'; }
      return strData;
    }
    

提交回复
热议问题