Strip whitespace from a string in-place?

后端 未结 3 2135
日久生厌
日久生厌 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:16

    void prepend(char* s,char ch){
        int len = strlen(s);
        memmove(s, s + 1, len - 1);
        s[len - 1] = '\x0';
    }
    
    
    void RemoveWhitespace(char* InStr, char ch){
         int n(0);
    
    if (InStr == NULL){
        return;
    }
    else if ((*InStr) == '\x0'){
        return;
    }   
    else if ((*InStr) != ch){
        RemoveWhitespace(InStr + 1,ch);
    }
    else{
        while ((*InStr) == ch){
            prepend(InStr,InStr[0]);
            n++;
        }
        RemoveWhitespace(InStr + n,ch);
    }
    }
    

提交回复
热议问题