Please help me with the task: "Remove double spaces"

Hello, I’m working on this task:

Write a program that removes all double spaces in a given string. It should read a string from the console and store it in the variable input. You should declare input by using var. Pay attention only to double spaces; we are not focusing on triple or more spaces in this task. For example:
>Are you ready to save the world?
Are you ready to save the world?

Here is my code:


namespace LearningVar
{
   class DoubleSpaces
   {
       static void Main(string[] args)
       {
           var input = Console.ReadLine();
           
           for (var i = 0; i < input.Length; ++i)
           {
               if (input[i] != ' ')
               {
                   Console.Write(input[i]);
               }
               Console.Write(input[++i]);
           }


       }
   }
}

Can anyone please help me to solve it?

My output for the code is "Are you ready to save the world? "

Hi Spydergirl1234,

In for loop, there is a good rule to not change the variable i inside the loop body, as you interfere with the for loop logic. So I suggest replacing all ++i inside the body of the loop.
The general logic for this task is like this: you check the current symbol and the next one. If both are spaces - you don’t output anything, otherwise - you output the current symbol. Be cautious to not get out of array bounds when checking the next symbol.

1 Like