Example:
Input string: "I love C programming!"
Output string: "I love C programming!"
Required knowledge
Basic C programming, Loop, String, FunctionSometimes it is often required to remove all extra blank space characters from a string. The string should only contain single blank space between two consecutive words. Here in this program we will be trimming out all extra blank spaces in a string.
Program to remove extra spaces from string
/** * C program to remove extra blank spaces from a given string */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_SIZE 100 //Maximum size of the string /* Function declaration */ char * removeBlanks(const char * string); int main() { char string[MAX_SIZE]; char * newString; printf("Enter any string: "); gets(string); printf("\nString before removing blanks: \"%s\"\n", string); newString = removeBlanks(string); printf("String after removing blanks: \"%s\"\n", newString); return 0; } /** * Removes extra blank spaces from the given string * and returns the new string with single blank spaces */ char * removeBlanks(const char * string) { int i, j; char * newString; newString = (char *)malloc(strlen(string) + 1); i = 0; j = 0; while(string[i] != '\0') { /* If blank space is found */ if(string[i] == ' ') { newString[j] = ' '; j++; /* Skip all further spaces */ while(string[i] == ' ') i++; } newString[j] = string[i]; i++; j++; } //Make sure that the string is NULL terminated newString[j] = '\0'; return newString; }
Output
Enter any string: I love C programming!
String before removing blanks: "I love C programming!"
String after removing blanks: "I love C programming!"
String before removing blanks: "I love C programming!"
String after removing blanks: "I love C programming!"
Happy coding ;)
You may also like
- String programming exercises index.
- C program to trim leading white space characters from a string.
- C program to trim trailing white space characters from a string.
- C program to trim both leading and trailing white space characters from a string.
- C program to remove first occurrences of a character in a string.
- C program to remove last occurrences of a character in a string.
- C program to remove all occurrences of a character in a string.
- C program to remove all occurrences of repeated characters in a string.
- C program to remove first occurrences of a word from a string.
- C program to remove last occurrences of a word from a string.
- C program to remove all occurrences of a word from a string.