rerere rerere - 2 months ago 9
C Question

Using Memmove to copy a string into itself produces wrong output

I'm given a string as such:

"Hello World"


With 5 Spaces characters inbetween the two words. I want to remove all but one of the spaces between the two words . However, my code seems to only work when there is 3 spaces or less. I'm using
memmove
to try and accomplish this.

Here is what I've tried:

int main(void) {
char * word = malloc(sizeof(char)*16);

strcpy(word,"Hello World");
checkWords(word);

return 0;
}

void checkWords(char * word) {
int i;
for(i=0; i < strlen(word); i++) {
if(word[i] == ' ' )
memmove(&word[i],&word[i+1],strlen(word)+1);
}

printf("The string without spaces is %s\n",word);
}


The output here is
"Hello World"

Not
"Hello World"


If It try input such as:

"Hello World" gets me "Hello World" -->correct

"Hello World" gets me "Hello World" -->correct


anything greater than 3 spaces, gets me incorrect output. (I want to have one space between the two words.

Answer

This works for me

for(i=0; i < strlen(word); i++) {
    if(word[i] == ' ' ) 
    {
        while (word[i+1] == ' ' && word[i+1] != '\0')
            memmove(&word[i],&word[i+1], strlen(word)-i);
    }
}