C program to remove all extra blank spaces from string
Learn how to write a C program to remove all extra blank spaces from a given string. This tutorial includes step-by-step instructions and code implementation to help you clean up strings by removing leading, trailing, and multiple spaces between words using basic string manipulation techniques.
In text processing, it is often necessary to clean up input by removing extra blank spaces from a string. This includes leading and trailing spaces as well as multiple spaces between words. This article will guide you through writing a C program to achieve this task using basic string manipulation techniques.
Steps to Solve the Problem
- Input the String: Read the input string from the user.
- Remove Extra Blank Spaces: Process the string to remove leading, trailing, and multiple spaces between words.
- Print the Result: Output the cleaned string.
Write a C program to remove all extra blank spaces from string
Here is the C program to remove all extra blank spaces from a given string:
#include <stdio.h>
#include <string.h>
int main() {
char str[200], result[200];
int i, j = 0;
// Input the string
printf("Enter the string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Removing trailing newline character
int len = strlen(str);
// Remove leading spaces
for (i = 0; i < len; i++) {
if (str[i] != ' ') {
break;
}
}
// Remove extra spaces
int space = 0;
for (; i < len; i++) {
if (str[i] != ' ') {
result[j++] = str[i];
space = 0;
} else if (str[i] == ' ' && space == 0) {
result[j++] = str[i];
space = 1;
}
}
// Remove trailing space if any
if (j > 0 && result[j - 1] == ' ') {
j--;
}
result[j] = '\0'; // Null terminate the result string
printf("String after removing extra spaces: '%s'", result);
return 0;
}
Output
Enter the string: learn programming at ProCoding
String after removing extra spaces: 'learn programming at ProCoding'
Explanation of the Code
- Input Handling: We read the input string using
fgets
and remove the trailing newline character usingstrcspn
. - Remove Leading Spaces:
- We iterate from the start of the string until we find the first non-space character.
- Remove Extra Spaces:
- We maintain a
space
flag to track if the current character is a space. - If the current character is not a space, we copy it to the
result
string and reset thespace
flag. - If the current character is a space and
space
is 0, we copy the space to theresult
string and set thespace
flag to 1. This ensures that consecutive spaces are reduced to a single space.
- We maintain a
- Remove Trailing Space:
- After processing the entire string, if the last character in the
result
string is a space, we remove it by decrementing the indexj
.
- After processing the entire string, if the last character in the
- Terminate the String:
- We null terminate the
result
string.
- We null terminate the
- Print the Result: We print the cleaned string.