Computer Science Canada

Remove duplicate spaces (in places)

Author:  DtY [ Wed Nov 11, 2009 10:57 pm ]
Post subject:  Remove duplicate spaces (in places)

As part of a project, I wanted to remove all duplicate spaces (ie, -- would become -, --- would become -, where each dash is a space), and I didn't need it to be in a different buffer, so I did it in place.
It works by overwriting the original buffer as it goes over the input. I haven't done any benchmarking, but it works pretty fast (near 2k file in no perceived time on my laptop).

C:
/*
    Removes duplicate spaces, in place
*/
void rmDblSpace(char *in, unsigned int length) {
    unsigned int inPlace, outPlace; /* Points to where the input and output
        are coming from/going to */
    inPlace = 0;
    outPlace = 0;
   
    while (inPlace <= length) {
        in[outPlace] = in[inPlace];
        outPlace++;
        if (in[inPlace] == ' ') {
            while (in[inPlace] == ' '){ inPlace++; }
        } else {
            inPlace++;
        }
    }
}

The reason that the length is taken in as an argument and not found with strlen() is because it's just one operation I need to do on a possibly large file, so to save time, I just passed the length in as an argument.

Go ahead and do what you want with it, take credit, what ever.


: