codescracker


c

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, is 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.

// Write a program in C to remove all 
// extra spaces from given String
// --------codescracker.com---------

#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:


« C Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test