C Program to remove all extra Spaces from given String

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:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char str[100], ch, count=0, len, i, j, temp;
    printf("Enter any string: ");
    gets(str);
    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];
            }
            len--;
            str[len]='\0';
            i = 0;
        }
    }
    printf("The new string after removing all extra spaces:\n");
    puts(str);
    getch();
    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:

  • Receive any string using gets() function inside any string variable say str
  • Calculate the length of the string using strlen() function and store it inside any variable say len
  • Create a for loop starts from 0 to one less than the length of the string, because indexing starts with 0
  • Inside the for loop, check whether any character and it's next character is equal to 32 or not. ASCII code 32 refers to space
  • If it is, then delete the next character (space), by placing each and every next character to previous one
  • After removing space, decrease the length of the string by one, and at last of the string, initialize a null terminated character ('\0') to tell the compiler that no any character left inside the string after that null terminated character
  • Initialize the loop variable i with 0 and continue
  • After removing all spaces, print the value of string as output, that will be the same string without extra spaces

C Online Test


« Previous Program Next Program »

Follow/Like Us on Facebook




Subscribe Us on YouTube