C program to remove extra spaces using string concepts.


Problem

Remove all the extra spaces from an entered string at runtime with the help of while loop by checking the 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 extra spaces between strings is as follows −

len = strlen(string);
for(i=0; i<len; i++){
   if(string[0]==' '){
      for(i=0; i<(len-1); i++)
      string[i] = string[i+1];
      string[i] = '\0';
      len--;
      i = -1;
      continue;
   }
   if(string[i]==' ' && string[i+1]==' '){
      for(j=i; j<(len-1); j++){
         string[j] = string[j+1];
      }
      string[j] = '\0';
      len--;
      i--;
   }
}

Example

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

#include<stdio.h>
int main() {
   char string[200];
   int i, j, len;
   printf("Enter a statement: ");
   gets(string);
   len = strlen(string);
   for(i=0; i<len; i++) {
      if(string[0]==' ') {
         for(i=0; i<(len-1); i++)
         string[i] = string[i+1];
         string[i] = '\0';
         len--;
         i = -1;
         continue;
      }
      if(string[i]==' ' && string[i+1]==' ') {
         for(j=i; j<(len-1); j++) {
            string[j] = string[j+1];
         }
         string[j] = '\0';
         len--;
         i--;
      }
   }
   printf("
New String after removing extra spaces is = %s", string);    getch();    return 0; }

Output

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

Enter a statement: Welcome to The world of C programming
New String after removing extra spaces is = Welcome to The world of C programming

Updated on: 25-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements