C program to remove spaces from a string

Removing spaces from a string.

In this article we will how to code a C program to remove spaces from a string. In order to do so we will use a while loop that will iterate each character of the string. Then if the character iterated by the while loop is not a blank space then we will store this character in a new string . And as the while loop ends our objective is achieved. 

C program to remove spaces from a string

Algorithm:

  • Initialize the variables.
  • Accept the input.
  • Initialize while loop and terminate it at the end of string.
  • Iterate each character through the loop.
  • Exclude spaces.
  • Store the string without spaces.
  • Print result.

C programming code to remove spaces from a string

Competitive Coding Techniques
#include  <stdio.h>
int main()
{
    
    //Initializing variables.
    char str[100], str_no_spc[100];
    int i=0, j=0 ;
    
    //Accepting inputs.
    printf("Enter the string:\n");
    gets(str);

    //Iterating each character of string. 
    while(str[i] != '\0')    
    {
        if(str[i] != ' ')  
        {
            
            str_no_spc[j++] = str[i];
        }
        
        i++;
    }
    str_no_spc[j] = '\0';
    //Printing result.
    printf("The string after removing all the spaces is:\n%s", str_no_spc);
    
    return 0;
}
Output:
Enter the string
PREP INSTA 
The string after removing all the spaces is:     
PREPINSTA 

One comment on “C program to remove spaces from a string”


  • kandukuri

    #include
    #include
    void main()
    {
    int i, j;
    char str[100];
    printf(“enter the string you want:”);
    gets(str);
    for (i = 0; str[i] != 0; i++)
    {
    while (str[i] == ‘ ‘ )
    {
    for (j = i; str[j] != 0; j++)
    {
    str[j] = str[j + 1];
    }
    str[j] = ‘\0’;
    }
    }
    printf(“the string is new one is %s”, str);
    }