- 0
Notifications Mark All Read
- Login
- Get Prime
C Program to Remove Spaces from a String
Removing spaces from a string.
In this article we will learn how to write a C program to remove spaces from a string.
Here we will store the string in a character array lets say str and that original string will contain the spaces in between.
Example:-
Input string: “Prep insta”
Output string: “Prepinsta”
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
#include<stdio.h> using namespace std; // Function to remove all spaces from a given string void removeSpaces(char *str) { // To keep track of non-space character count int count = 0; // Traverse the provided string. If the current character is not a space, //move it to index 'count++'. for (int i = 0; str[i]; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is incremented str[count] = '\0'; } // Driver program to test above function int main() { char str[] = "P re p i n sta "; removeSpaces(str); printf("%s", str); return 0; }
Output
Prepinsta
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
#include
#include
int removespaces(char *str)
{
int traverse;
for(traverse = 0; str[traverse]; traverse += 1)
{
if(str[traverse] == ‘ ‘)
{
continue;
}
printf(“%c”,str[traverse]);
}
}
void main()
{
char str[100];
scanf(“%[^\n]”,str);
removespaces(str);
}
#python code
n=input()
a=[]
for i in n:
if i!=’ ‘:
a.append(i)
print(*a,sep=””)
#include
#include
main()
{
int i;
int j;
char str[100];
printf(“enter a string with space”);
gets(str);
for(i=0;str[i]!=’\0′;i++)
{
if(str[i]==’ ‘)
{
for(j=i;str[j]!=’\0’;j++)
{
str[j]=str[j+1];
}
}
}
puts(str);
}
#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);
}