views:

660

answers:

3

Well I'm looking for a function that reduce multiple spaces in a string.

For example for string s given :

s="hello__________world____!"

The function must return "hello_world_!"

In python we can do it via regexp simply as:

re.sub("\s+", " ", s);
+1  A: 

There is no such function in the C standard library. One must write a function to do so or use a third-party library.

The following function should do the trick. Use the source string as the destination pointer to perform the operation in place. Otherwise, ensure that the destination buffer is sufficiently sized.

void
simplifyWhitespace(char * dst, const char * src)
{
    for (; *src; ++dst, ++src) {
        *dst = *src;
        if (isspace(*src))
            while (isspace(*(src + 1)))
                ++src;
    }

    *dst = '\0';
}
Judge Maygarden
+2  A: 
void remove_more_than_one_space(char *dest, char *src)
{
    int i, y;
    assert(dest && src);
    for(i=0, y=0; src[i] != '\0'; i++, y++) {
        if(src[i] == ' ' && src[i+1] == ' ') {
            /* let's skip this copy and reduce the y index*/
            y--;
            continue;
        }
        /* copy normally */
        dest[y] = src[i];
    }
    dest[y] = '\0';
}
int main()
{
    char src[] = "Hello   World   ! !!   !";
    char dest[strlen(src) + 1];
    remove_more_than_one_space(dest, src);

    printf("%s\n", dest);
}

I just made this, hope it helps.

Luca Matteis
But the caller needs to be sure that dest points to a block that is larger that strlen(src) or this will trash memory.
Stephen C
Why larger? dest must be *at least* the same size of src.
Luca Matteis
strlen(src) i mean
Luca Matteis
@Luca: If it must be only *at least* `strlen(src)` then why does your code go `char dest[strlen(src) + 1];`? ;)
Sean Nyman
It's worked. The function return string trimmed but with a special char at the end.
mezgani
@Sean Nyman: Argh, yes strlen(src) + 1 :)
Luca Matteis
@mezgani: i fixed the problem, i was adding 1 after the iteration for the NULL character, but there wasn't the need for it.
Luca Matteis
+2  A: 

A version that modifies the string in place, run it on a copy if the original must be preserved:

void compress_spaces(char *str)
{
        char *dst = str;

        for (; *str; ++str) {
                *dst++ = *str;
                if (isspace(*str)) {
                        do ++str; while (isspace(*str));
                        --str;
                }
        }
        *dst = 0;
}
Idelic