C Program to remove all extra Spaces from given String

« C Tutorial C Examples »

In this tutorial, we will learn about how to remove all the extra spaces from any given string (by user at run-time). In this program, if user supplies any string that contains more than one spaces between any two words, then all the extra spaces will be removed and between any two word, there will only be one single space.

The question is, write a program in C to remove all extra spaces from a given string. The program given below is answer to this question:

int main()
    char str[100], ch, count=0, len, i, j, temp;
    printf("Enter any string: ");
    len = strlen(str);
    for(i=0; i<len; i++)
        if(str[i]==32 && str[i+1]==32)
            temp = i;
            for(j=i; j<(len-1); j++)
                str[j] = str[j+1];
            i = 0;
    printf("The new string after removing all extra spaces:\n");
    return 0;

The above program was build and run under Code::Blocks IDE, therefore here is the first snapshot of the sample run:

c remove extra spaces from string

Provide any string with extra spaces and press ENTER key to see the output as shown here in the second snapshot of the sample run:

remove extra spaces c

Here are some of the main steps used in above program:

C Online Test

« C Tutorial C Examples »

© Copyright 2021. All Rights Reserved.