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

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

    Ok this is my take on the question. I believe it's the most concise solution that modifies the string in place (free will work) and avoids any UB. For small strings, it's probably faster than a solution involving memmove.

    void stripWS_LT(char *str)
    {
        char *a = str, *b = str;
        while (isspace((unsigned char)*a)) a++;
        while (*b = *a++)  b++;
        while (b > str && isspace((unsigned char)*--b)) *b = 0;
    }
    

提交回复
热议问题