Strip whitespace from a string in-place?

后端 未结 3 2065
日久生厌
日久生厌 2021-02-06 04:28

I saw this in a \"list of interview questions\". Got me wondering.

Not limited to whitespace necessarily, of course, easily generalized to \"removing some specific char

3条回答
  •  隐瞒了意图╮
    2021-02-06 05:05

    First of all, i is always an inefficient idiom for looping over a string. The correct loop condition is simply str[i], i.e. loop until str[i] is the null terminator.

    With that said, here's the simplest/most concise algorithm I know:

    for (size_t i=0, j=0; s[j]=s[i]; j+=!isspace(s[i++]));
    

    Note: My solution is for the question as written in the subject (whitespace) as opposed to the body (particular character). You can easily adapt it if needed.

提交回复
热议问题