C

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

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *