Remove extra white spaces in C++

前端 未结 12 1831
日久生厌
日久生厌 2021-02-05 12:01

I tried to write a script that removes extra white spaces but I didn\'t manage to finish it.

Basically I want to transform abc sssd g g sdg gg gf into

12条回答
  •  太阳男子
    2021-02-05 12:14

    Here's a simple, non-C++11 solution, using the same remove_extra_whitespace() signature as in the question:

    #include 
    
    void remove_extra_whitespaces(char* input, char* output)
    {
        int inputIndex = 0;
        int outputIndex = 0;
        while(input[inputIndex] != '\0')
        {
            output[outputIndex] = input[inputIndex];
    
            if(input[inputIndex] == ' ')
            {
                while(input[inputIndex + 1] == ' ')
                {
                    // skip over any extra spaces
                    inputIndex++;
                }
            }
    
            outputIndex++;
            inputIndex++;
        }
    
        // null-terminate output
        output[outputIndex] = '\0';
    }
    
    int main(int argc, char **argv)
    {
        char input[0x255] = "asfa sas    f f dgdgd  dg   ggg";
        char output[0x255] = "NO_OUTPUT_YET";
        remove_extra_whitespaces(input,output);
    
        printf("input: %s\noutput: %s\n", input, output);
    
        return 1;
    }
    

    Output:

    input: asfa sas    f f dgdgd  dg   ggg
    output: asfa sas f f dgdgd dg ggg
    

提交回复
热议问题