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

后端 未结 30 2402
一个人的身影
一个人的身影 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条回答
  •  旧时难觅i
    2020-11-22 02:48

    My solution. String must be changeable. The advantage above some of the other solutions that it moves the non-space part to the beginning so you can keep using the old pointer, in case you have to free() it later.

    void trim(char * s) {
        char * p = s;
        int l = strlen(p);
    
        while(isspace(p[l - 1])) p[--l] = 0;
        while(* p && isspace(* p)) ++p, --l;
    
        memmove(s, p, l + 1);
    }   
    

    This version creates a copy of the string with strndup() instead of editing it in place. strndup() requires _GNU_SOURCE, so maybe you need to make your own strndup() with malloc() and strncpy().

    char * trim(char * s) {
        int l = strlen(s);
    
        while(isspace(s[l - 1])) --l;
        while(* s && isspace(* s)) ++s, --l;
    
        return strndup(s, l);
    }
    

提交回复
热议问题