Q:

C program to remove all spaces from a given string

belongs to collection: C String Programs

0

C program to remove all spaces from a given string

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"

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to convert a string to sentence case... >>
<< C program to copy one string to another and count ...