Home »
C 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
Problem statement
Given a string with spaces and we have to remove all spaces from it using C program.
Removeing all spaces from a given string
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
C String Programs »