C Program to remove all the blank spaces in a character string

      This C program makes a new string from the existing string. While making a new string it checks every character of an input string and then it omits spaces by checking against condition (a[i]!=’ ‘). So by the end of the loop, the new string is made by remove all the blank spaces from the existing string.

c program to remove all the blank spaces in a character string



Source Code :

#include<stdio.h>
#include<tstring.h>
int main()
{
    char a[80],t[80];
    int i,j;
    printf("\n Enter the text:");
    gets(a);                                         // Step 1
    for(i=0,j=0; a[i]!='\0'; ++i)                    // Step 2 
        if(a[i]!= ' ' )                              // Step 2 (i)
            t[j++]=a[i];                             // Step 2(ii)
    t[j]='\0';                                       // Step 3
    printf("\n The text without blank spaces :");
    puts(t);                                         // Step 4
    return 0;
}


edit-code-image

Sample Test cases :

1. Enter the text : s h rgg
   The text without blank spaces : shrgg
   
2. Enter the text : as i am 
   The text without blank spaces : asiam

3. Enter the text : hai i am
   The text without blank spaces : haiiam

Explanation:

Step 1 : The string is read from the user using gets() function.

Step 2 : Every character of the input string is read using for loop.

Step 2 (i) : Every character in the input string is checked whether it is space or not using (a[i]!=’ ‘) condition.

Step 2 (ii): if character is not space then it is copied to new string.

Step 3 : The new string is appended with ‘\0’ character at the end of for loop.

Step 4 : Finally the string without any spaces is printed on output screen using puts() function.

More Content :Explore More