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.

Example

Input

Input string: Learn     C      programming at  Codeforwin.

Output

String after removing extra blanks: 
"Learn C programming at Codeforwin"

Required knowledge

Basic C programming, Loop, String, Function

Must know – Program to copy one string to another

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: Learn     C      programming at  Codeforwin.

String before removing blanks: 
'Learn     C      programming at  Codeforwin.'

String after removing blanks: 
'Learn C programming at Codeforwin.'

Happy coding 😉