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

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

    Just to keep this growing, one more option with a modifiable string:

    void trimString(char *string)
    {
        size_t i = 0, j = strlen(string);
        while (j > 0 && isspace((unsigned char)string[j - 1])) string[--j] = '\0';
        while (isspace((unsigned char)string[i])) i++;
        if (i > 0) memmove(string, string + i, j - i + 1);
    }
    

提交回复
热议问题