C program to remove spaces, blanks from a string

Write a C program to remove extra spaces, blanks from a string. How to remove extra blank spaces, blanks from a given string using functions in C programming. Logic to remove extra white space characters from a string in C.

Required knowledge

Basic C programming, C if-else, C for loop, Array, functions, Strings

Logic to remove extra spaces, blanks

  1. Input string from user, store it in some variable say str.
  2. Declare another string newString with same size as of str, to store string without blanks.
  3. For each character in str copy to newString. If current character in str is white space. Then copy single white space to newString and rest white spaces in str.

Program to remove extra spaces from string

/** * C program to remove extra blank spaces from a given string */ #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 // Maximum string size /* Function declaration */ char * removeBlanks(const char * str); int main() { char str[MAX_SIZE]; char * newString; printf("Enter any string: "); gets(str); printf("\nString before removing blanks: \n'%s'", str); newString = removeBlanks(str); printf("\n\nString after removing blanks: \n'%s'", newString); return 0; } /** * Removes extra blank spaces from the given string * and returns a new string with single blank spaces */ char * removeBlanks(const char * str) { int i, j; char * newString; newString = (char *)malloc(MAX_SIZE); i = 0; j = 0; while(str[i] != '\0') { /* If blank space is found */ if(str[i] == ' ') { newString[j] = ' '; j++; /* Skip all consecutive spaces */ while(str[i] == ' ') i++; } newString[j] = str[i]; i++; j++; } // NULL terminate the new string 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'
Process returned 0 (0x0) execution time : 11.266 s



Instagram