C program to remove spaces in a sentence using string concepts.

CServer Side ProgrammingProgramming

Problem

Remove all the spaces from an entered string at runtime with the help of while loop by checking spaces at each index of a character.

Solution

Consider an example given below −

It removes all the spaces from a given string. The given string is Tutorials Point C Programming. The result after removing spaces is TutorialsPointCProgramming.

An array of characters is called a string.

Given below is the declaration of a string −

char stringname [size];

For example, char string[50]; string of length 50 characters.

Initialization

  • Using single character constant.
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants.
char string[10] = “Hello”:;

Accessing

There is a control string “%s” used for accessing the string till it encounters ‘\0’.

The logic we used to remove the spaces between strings is as follows −

while(string[i]!='\0'){
   check=0;
   if(string[i]==' '){
      j=i;
      while(string[j-1]!='\0'){
         string[j] = string[j+1];
         j++;
      }
      check = 1;
   }
   if(check==0)
   i++;
}

Example

Following is the C program to remove all the spaces in a sentence by using the string concepts −

#include<stdio.h>
int main() {
   char string[50];
   int i=0, j, check;
   printf("Enter any statement: ");
   gets(string);
   while(string[i]!='\0') {
      check=0;
      if(string[i]==' ') {
         j=i;
         while(string[j-1]!='\0') {
            string[j] = string[j+1];
            j++;
         }
         check = 1;
      }
      if(check==0)
      i++;
   }
   printf("\nSentence without spaces: %s", string);
   getch();
   return 0;
}

Output

When the above program is executed, it produces the following output −

Run 1:
Enter any statement: Tutorials Point C Programming
Sentence without spaces: TutorialsPointCProgramming
Run 2:
Enter any statement: Welcome to the world of tutorials
Sentence without spaces: Welcometotheworldoftutorials
raja
Published on 25-Mar-2021 08:28:08
Advertisements