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

后端 未结 30 2604
一个人的身影
一个人的身影 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:31

    This is the shortest possible implementation I can think of:

    static const char *WhiteSpace=" \n\r\t";
    char* trim(char *t)
    {
        char *e=t+(t!=NULL?strlen(t):0);               // *e initially points to end of string
        if (t==NULL) return;
        do --e; while (strchr(WhiteSpace, *e) && e>=t);  // Find last char that is not \r\n\t
        *(++e)=0;                                      // Null-terminate
        e=t+strspn (t,WhiteSpace);                           // Find first char that is not \t
        return e>t?memmove(t,e,strlen(e)+1):t;                  // memmove string contents and terminator
    }
    

提交回复
热议问题