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

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

    I'm not sure what you consider "painless."

    C strings are pretty painful. We can find the first non-whitespace character position trivially:

    while (isspace(* p)) p++;
    

    We can find the last non-whitespace character position with two similar trivial moves:

    while (* q) q++;
    do { q--; } while (isspace(* q));
    

    (I have spared you the pain of using the * and ++ operators at the same time.)

    The question now is what do you do with this? The datatype at hand isn't really a big robust abstract String that is easy to think about, but instead really barely any more than an array of storage bytes. Lacking a robust data type, it is impossible to write a function that will do the same as PHperytonby's chomp function. What would such a function in C return?

提交回复
热议问题