Thursday, May 21, 2015

C : Program to replace multiples spaces with a single space

Earlier we have seen C program to count blanks and tabs , with using the same code, lets try to write another program which takes a line of words/characters and parses through it checking for multiple spaces and replaces them with single space.

For example, in  below line
This     line has      multiple        spaces    between     words.

Ideally while typing a sentence we leave a single space between word-to-word.  This sentence has multiple spaces which can be removed and replaced with single space by our program below.

This line has multiple spaces between words.
  #include <stdio.h>   
  int main()   
  {   
   int c;   
   printf("Enter a line to replace multiple spaces with single space\n");   
   /* Read character by character and prase till end of the file */  
   while((c=getchar()) != '\n')   
   {   
    if(c == ' ')   
    {   
     /* Notice semi-colon at end of below line. It reads a character and if its space  
      it discards it and read character again till its not a space*/  
     while( (c=getchar()) == ' ');   
      /* Now just output single space */  
      putchar(' ');   
    }   
    putchar(c);   
   }   
   printf("\n");   
   return 0;   
  }   
From above code,
  • Using while loop, we start reading character by character with getchar()
  • First character is read and checked for end of the line
  • If not End of the line ('\n'), check if it's a space
  • If its a space, discard spaces by reading them in a while loop.  Note semi-colon at end of the while loop.
  • Now output a single space and read next character.
  • Finally print a new line and return.
Output of this program,
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
 Enter a line to replace multiple spaces with single space  
 This program  replaces       multiple spaces    with   single  space  
 This program replaces multiple spaces with single space  


No comments:

Post a Comment