C Program to Remove Extra Space Characters From a String

  • Write a C program to delete extra space characters from a string.

Given a string containing multiple space characters, we have to remove extra spaces from string. If a string contains more than one consecutive space, then we should remove all consecutive spaces except one.
For Example
If input string is "Tech   Crash     Course"
Output string should be "Tech Crash Course".

C program to remove or delete extra spaces from string

We first take a string as input from user using gets function. Using a for loop, we iterate from first character to last character of input string and check whether current character is a space character or not. If last character was not a space character then we copy this space character to output string otherwise skip this space character. At last we add a null character at the end of output string. In this program we are using an extra character array of same size as input array, the space complexity of this algorithm is O(n) and as we are traversing input array only once the time complexity also becomes O(n).

/*
* C Program to remove extra spaces
*/
#include <stdio.h>
#include <conio.h>
#include <string.h>

int main(){
    char inputString[100], outputArray[100];
    int readIndex = 0, writeIndex;
    printf("Enter a String \n");
    gets(inputString);
    /* Skips all spaces before first characters */
    while(inputString[readIndex] == ' '){
        readIndex++;
    }

    for(writeIndex = 0;inputString[readIndex] != '\0'; readIndex++){
      if(inputString[readIndex]==' ' && inputString[readIndex-1]==' '){
          continue;
      }
      outputArray[writeIndex] = inputString[readIndex];
      writeIndex++;
    }
    outputArray[writeIndex] = '\0';
    printf("String without extra spaces\n%s", outputArray);

    getch();
    return 0;
}
Program Output
Enter a String 
Tech   Crash    Course
String without extra spaces
Tech Crash Course
We can also solve this problem without using any extra output character array. In this case we can modify and remove extra spaces from input array.

Related Topics
C program to remove vowels from a string
C program to swap two strings
C program to convert lowercase string to uppercase
C program to convert uppercase string to lowercase
C program to check if two strings are anagram
C program to find a substring from a given string
C program to check string is palindrome
List of all C programs