Home » C solved programs » C string programs

C program to remove all spaces from a given string



In this C program, we are going to learn how to remove all spaces from a given string? Here, we will have a string with spaces and program will remove all spaces and print the string without spaces.
Submitted by IncludeHelp, on April 05, 2018

Given a string with spaces and we have to remove all spaces from it using C program.

Without using other temporary string, in this program - we are reading a string from the user and then printing the string (by updating the same string variable) after removing all spaces from it.

Example:

    Input:
    String: "C is the master of all"
    Output:
    String: "Cisthemasterofall"

    Input:
    String: "I love includehelp.com"
    Output;
    String:  "Iloveincludehelp.com"

Program to remove all spaces from a given string in C


/** C program to create a new string after
 * removing spaces from the string
*/

#include <stdio.h>

// function to remove white spaces from the string
void remove_spaces(char *buf , int len)
{
    int i=0,j=0;
    char temp[100]={0};
    
    for(i=0,j=0 ; i<len ; i++)
    {
        if(buf[i] == ' ' && buf[i]!=NULL)
        {
            for(j=i ; j<len ; j++)
            {
                buf[j] = buf[j+1];
            }
            len--;
        }
    }
}

// main function
int main()
{
    // declare a char buffer
    char string[100]={0};
    
    // declare some local int variables
    int i=0,len=0;
    
    printf("\nEnter your string : ");
    gets(string);
    
    // calculate the length of the string
    len = strlen(string);
    
    remove_spaces(string , len);
    
    printf("\nNew string is : %s\n",string);
    return 0;
}

Output

    Run 1 : 
    Enter your string : C is the master of all
    New string is : Cisthemasterofall

    Run 2 : 
    Enter your string : I love includehelp.com
    New string is : Iloveincludehelp.com





Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.