Clarity Clarity - 16 days ago 5
C# Question

int variable = sentence.Length won't work but sentence.Length will

The objective of the code is to remove the positions where there are 2+ spaces together, and replace them with a single space.

static void Main(string[] args)
{
string sentence = Console.ReadLine();
int size = Convert.ToInt16(sentence.Length);

for (int i = 0; i < size - 1; i++)
{
sentence = sentence.Trim();
while ((sentence[i] == ' ' ) && (sentence[i+1] == ' '))
{
sentence = sentence.Remove(i + 1, 1);
}
}

Console.WriteLine(sentence);
Console.ReadLine();
}


for some reason this code won't work if you throw 2 or more spaces.
But this one works, if you use sentence.Length , instead of size variable above.

static void Main(string[] args)
{
string sentence = Convert.ToString(Console.ReadLine());
for (int i = 0; i < sentence.Length - 1; i++)
{
while ((sentence[i] == ' ') && (sentence[i + 1] == ' '))
{
sentence = sentence.Remove(i + 1, 1);
}
}
Console.WriteLine("Sentence:{0}", sentence);
Console.ReadLine();
}


Why won't the first snippet work?

Answer

Because sentence.Length - 1 will increase or decrease the size of the string accordingly if u remove chars from the string. Whereas size - 1 is fixed before the loop and it would give you Index was outside the bounds of the array. So in the first case you get the error. But in the second case your program runs successfully.

Dry run is the technique where you can see what would happen when your program receives some input and then step over every step in the loop like a debugger.