C Program To Replace Multiple Spaces With Single Space
In this tutorial, we are going to see how to write a C program to replace multiple spaces with single space. For example, let’s consider the following string “Welcome to StackHowTo”. There are multiple spaces in this string, so our program will display the string as “Welcome to StackHowTo”. It will replace multiple spaces with a single space when they appear more than once in a string.
C Program To Replace Multiple Spaces With Single Space
#include <stdio.h> int main() { char str[100], res[100], i = 0, j = 0; printf("Enter a string: "); gets(str); while (str[i] != '\0') { if ((str[i] == ' ' && str[i+1] == ' ') != 1) { res[j] = str[i]; j++; } i++; } res[j] = '\0'; printf("After replacing spaces with single space: %s", res); return 0; }
Output:
Enter a string: Welcome to StackHowTo After replacing spaces with single space: Welcome to StackHowTo