Remove blank spaces from a string in C

Here, we will learn to make C program to remove space from a string. We will take input and check if there are more than one space at a place. Then we will remove extra space from given string.

Consider a user gives the string “I        am          learning C       programming” to remove extra space from this. Then we will print the output string like “I am learning C programming“. So, let’s go to the code bellow.

C program to remove blank space from a string

// c program to remove extra blank spaces

#include <stdio.h>

int main(){
   char text_string[200], blank_string[200];
   int t, x = 0, y = 0;

   printf("Enter your string here : \n");
   gets(text_string);

   while(text_string[x] != '\0'){
        
      if(text_string[x] == ' '){
         t = x + 1;
   
         if(text_string[t] != '\0'){
                
            while(text_string[t] == ' ' && text_string[t] != '\0'){
               if(text_string[t] == ' '){
                  x++;
               }
               t++;
            }
         }
      }
      blank_string[y] = text_string[x];
      x++;
      y++;
   }

   blank_string[y] = '\0';

   printf("\nGiven string after removing extra blanks is : \n%s\n", blank_string);

   return 0;
}

Output of remove space program:

remove-space-from-string-c-program-to-remove-extra-space-from-string

You can also make this program using function which will take the string as argument then remove all extra space from it. Now, let’s see how can we make this program using pointer in C. Let’s write the code bellow.

Remove space using pointer in C

// c program to remove extra blank spaces

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SPACE ' '

char *space_removing(char *cha){
    char *begin;
    int t, i, j, len;

    i = j = 0;

    len = strlen(cha);

    begin = (char*)malloc(len + 1);

    if(begin == NULL){
       exit(EXIT_FAILURE);
    }

    while(*(cha + i) != '\0'){

       if(*(cha + i) == ' '){
          t = i + 1;

          if(*(cha + t) != '\0'){

             while(*(cha + t) == ' ' && *(cha + t) != '\0'){
                if(*(cha + t) == ' '){
                   i++;
                }
                t++;
             }
          }
       }
       *(begin + j) = *(cha + i);
       i++;
       j++;
    }
    *(begin + j)= '\0';

    return begin;
}

int main(){
   char *pt, main_strg[200];

   printf("Enter The main string here : \n");
   gets(main_strg);

   pt = space_removing(main_strg);
   printf("\nGiven string after removing spaces is : \n%s\n", pt);

   free(pt);

   return 0;
}

Program output:

Enter The main string here :
Learn        to     remove space

Given string after removing spaces is :
Learn to remove space

Previous pageSort string

Next pageSwap string