In this C program, we will delete extra space characters from a 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 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).
#include <stdio.h> #include <string.h> int main(){ char inputString[100], outputArray[100]; int readIndex = 0, writeIndex = 0; printf("Enter a String \n"); gets(inputString); while(inputString[readIndex] == ' '){ readIndex++; } for(;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); return 0; }Output
Enter a String Tech Crash Course String without extra spaces Tech Crash CourseWe 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