C program to remove blank space from string

In this tutorial we are going to write a program to remove all blank spaces available in the string. The logic we are going to use will be very similar to the below program.

You can check it out

C program to replace blank space of string with given character.

How our space removal program will work?

  • Our program will take a string as an input.
  • Now using if check we will find the space available in the string.
  • Our logic will be, if space will come just shift the character by one index towards left.
  • After doing this, we will see all blank space has removed.

Program in C to remove blank space from String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<stdio.h>
#include<string.h>
void main(){
     char str[100],c;
     int i,j,len;
     printf("C Program to remove space from string \n");
     printf("enter the string : \n");
     scanf("%[^\n]",str);
    len = strlen(str);
    for(i=0; i<len; i++)
    {
        if(str[i] == ' ')
        {
            for(j=i; j<len; j++)
            {
                str[j] = str[j+1];
            }
            len--;
            i--;
        }
    }
     printf("String after removing space: %s", str);
 }

Output

Program in C to remove blank space from String

[wpusb]