Tuesday, December 9, 2014

Program in C to replace each string of one or more blanks by a single blank.

The following program strives to give a solution to the problem of replacing each string of one or more blanks , as present in the inputted text, by a single blank.




Program Without Comments :


/*Program in C to replace each string of one or more blanks by a single blank.*/
#include<stdio.h>
int main(){
char s[200];
int t=0;
int i=0;
printf("Enter your text :\n");
scanf("%[^\n]s",s);
while(s[i]!='\0'){
if(s[i]==' '){
   ++t;
          }else{
          if(t>0){
              t=0;
              printf(" ");
              printf("%c",s[i]);
                 }else{
                    printf("%c",s[i]);
                      }
               }
++i;
               }
return 0;
}



Program with comments :

/*Program in C to replace each string of one or more blanks by a single blank.*/
#include<stdio.h>
int main(){
char s[200]; /*Declare a char array , big enough to hold the inputted text*/
int space=0;     /*to count the number of spaces*/
int i=0;     /*The index value holder ,to traverse the char array*/
printf("Enter your text :\n");
scanf("%[^\n]s",s);  /*We'll scan the text till the ENTER Key is pressed.*/
while(s[i]!='\0'){   /*Check to determine the end of char array*/
if(s[i]==' '){      
   ++space;         
          }else{
          if(space>0){  /*space>0 would signify that we just traversed more than 1 'space' characters */
              space=0; /*we'll put space=0*/
              printf(" "); /*Since we just traversed more than 1 space , we print a single space character instead of all of the traversed spaces*/
              printf("%c",s[i]); /*Next we print the current non-space character*/
                 }else{
                    printf("%c",s[i]); /*Else we just print the current character as we did not encounter one or more than one space  characters*/
                      }
               }
++i;
               }
return 0;
}


No comments:

Post a Comment