C Program to Remove All Spaces from a String
Write a C program to remove all spaces from a string.
- Reads characters from the user one by one until newline (\n) is encountered.
- Stores the null terminator (\0) to properly mark the end of the original string.
- Copies only non-space characters from the original string into a new string.
- Prints the final string without any spaces using the result array.
Example : pgm.c
#include <stdio.h> int main() { char str[100], result[100]; int i = 0, j = 0; printf("Enter a string: "); while ((str[i] = getchar()) != '\n') { i++; } str[i] = '\0'; // Remove spaces for (i = 0; str[i] != '\0'; i++) { if (str[i] != ' ') { result[j] = str[i]; j++; } } result[j] = '\0'; printf("String without spaces: %s\n", result); return 0; }
Output :
Enter a string: Hello World
String without spaces: HelloWorld
String without spaces: HelloWorld