Strip whitespace from a string in-place?

后端 未结 3 2070
日久生厌
日久生厌 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<strlen(str) 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.

    0 讨论(0)
  • 2021-02-06 05:12

    C doesn't have default arguments, and if you're programming in C++ you should use std::string and remove_if from <algorithm>.

    You definitely can make this more efficient, by eliminating the calls to strlen, which are turning an O(N) algorithm into an O(N2) algorithm, and are totally unnecessary -- you're scanning the string anyway, so just look for the NUL yourself.

    You can also make this more C-idiomatic, by using two pointers instead of array indexing. I'd do it like this:

    void strip_char(char *str, char strip)
    {
        char *p, *q;
        for (q = p = str; *p; p++)
            if (*p != strip)
                *q++ = *p;
        *q = '\0';
    }
    
    0 讨论(0)
  • 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);
    }
    }
    
    0 讨论(0)
提交回复
热议问题