1

Input- Hello World

output- HelloWorld

This is program i have written in c.

But i get segmentation fault.

The logic i have used is, when i found a space i swap that with next character till end then insert a '\0' character

#include <stdio.h>

int main()    
{    
        char s[12]="Hello World";    
        char *t;    
        t=s;    
        while(*t)    
        {    
                char *p;    
                p=t;    
                if(*p==' ')    
                {    
                        while(*p !='\0')    
                        {    
                                char x;    
                                x=*p;   
                                *p=*(p+1);    
                                *(p+1)=x;   
                                p++;    
                        }    
                        *(p-1)='\0';    
                }    
                t++;   
        }
        printf("%s\n",s);   
}
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190

4 Answers4

3

K&R style copy:

#include <stdio.h>

int main()
{
        char s[12]="Hello World";
        char *src, *dst;
        for(src=dst=s; *dst = *src; src++) {
                if( *dst == ' ') continue;
                dst++;
                }
        printf("%s\n",s);
        return 0;
}
wildplasser
  • 43,142
  • 8
  • 66
  • 109
1

swap out the nasty nested while loop with a call to this function.

void siftLeftAtCurrentPos(char* cstr)
{
   while(*cstr)
   {
     *cstr = *(cstr + 1);
      cstr++;
   }
}

then don't increment t until *p != ' '

Jonathan Henson
  • 8,076
  • 3
  • 28
  • 52
0

Just take out:    

char x;    
x=*p;   
*(p+1)=x;

This is the problem.

Jiminion
  • 5,080
  • 1
  • 31
  • 54
0

Your inner while loop is an infinite loop. When you swap the space you end up making so that the next character will also be a space.

As mentioned in Jonathan's answer, you can fix this by just shifting things left instead of swapping the values. That said, you can make an even more efficient algorithm that removes spaces in a single pass, without nested loops. Your current algorithm will take quadratic time if you have a string that is full of spaces...

char* in = s; //next character to read;
char* out = s; //where to write the next non-space character;
//copy all the non spaces
while(*in){
   if(*in != ' '){
     *out = *in;
     out++;
   }
   in++;
}
//now fill the rest of the strings with null values:
while(out != in){
   *out = '\0';
   out++;
}
hugomg
  • 68,213
  • 24
  • 160
  • 246