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. Program to remove excess white space characters from a string in C.

Example:
Input string: "I    love    C    programming!"
Output string: "I love C programming!"

Required knowledge

Basic C programming, Loop, String, Function

Sometimes 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!"

Happy coding ;)


You may also like

Labels: , ,