3

Well I'm looking for a function that reduce multiple space characters ' ' 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);
3
  • 1
    Show what you have tried so far. Commented Aug 1, 2009 at 23:13
  • What have you done so far to try to solve this? Commented Aug 1, 2009 at 23:15
  • i thought to a function that can reduce the multispaces, but it does not work, may be for recursion problem Commented Aug 1, 2009 at 23:35

6 Answers 6

8

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I have executed this function but if i insert " Empty somehow " i will receive 0 output! I claim this is not doing what its supposed to do...
Works for me on your input. I don't get what you mean by "receive 0 output". I claim you're wrong. ;-)
when i compile this statement and enter a char* it will remove all the elements, my input was " Empty somehow " and the result was "" so literally empty, i would be glad if you tell me what i do wrong :-)
@Idelic How come you do ++str. Is it the same as str++ in this situation?
4

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';
}

Comments

2
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.

5 Comments

But the caller needs to be sure that dest points to a block that is larger that strlen(src) or this will trash memory.
Why larger? dest must be at least the same size of src.
@Luca: If it must be only at least strlen(src) then why does your code go char dest[strlen(src) + 1];? ;)
It's worked. The function return string trimmed but with a special char at the end.
@mezgani: i fixed the problem, i was adding 1 after the iteration for the NULL character, but there wasn't the need for it.
1
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
    char word[100];
    gets(word);
    //the word has more than a single space in between the words
    int i=0,l,j;
    l=strlen(word);
    for (i=0;i<l;i++)
    {
        if(word[i]==' '&&word[i+1]==' ')
        {
            for(j=i+1;j<l;j++)
            word[j]=word[j+1];
        }
    }
    puts(word);
    return 0;
}

This code is very simple and it worked like a charm for me. I don't know if this code will have some other problems I haven't come across, but for now this works.

Comments

0

I'm just learning C, so I'm using much more basic code. I'm reading the first chapter of "The C programming language", and I was trying to find the answer to a task set in there.

This is what I came up with:

#include <stdio.h>

int main()
{
    /* Set two integers:
       c is the character being assessed,
       lastspace is 1 if the lastcharacter was a space*/
    int c, lastspace;
    lastspace = 0;

    /* This while loop will exit if the character is EOF

       The first "If block" is true if the character is not a space,
       and just prints the character
       It also tells us that the lastcharacter was not a space

       The else block will run if the character is a space

       Then the second IF block will run if the last character
       was not also a space (and will print just one space) */

    while((c = getchar()) != EOF){
        if (c != ' '){
            putchar(c);
            lastspace = 0;
        }
        else {
            if (lastspace != 1)
                    putchar(c);
            lastspace = 1;
        }
    }

    return 0;
}

Hope that helps! Also, I am well aware that this code is perhaps not optimised, but it should be simple for a beginner like me to understand!

Thanks, Phil

Comments

0

another way of doing this to print only the first occurrence of space until next character comes, here is my brute force solution.

#include<stdio.h>
typedef int bool;
#define True  1
#define False 0
int main()
{
        int t;
        bool flag = False;

        while ((t = getchar()) != EOF)
                if (t == ' ' && !flag)
                {
                        putchar(' ');
                        flag = True; // flag is true for the first occurence of space
                }

                else if(t == ' '&& flag)
                        continue;
                else
                {
                        putchar(t);
                        flag = False;
                }

        return 0;
}

hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.