-2

I know it's a simple question but can someone help me figure out how to convert this while loop to a for loop. I keep getting an error trying to convert it

static string CountLines(string s)
{
    long count = 0;
    int start = 0;

    while ((start = s.IndexOf('\n', start)) != -1)
    {
        count++;
        start++;
    }
    return count.ToString();

}

This is the way I tried

for (int start = 0; start !=-1 ; start = s.IndexOf('\n', start)) {
   count++;
   start++;
}
johnny 5
  • 19,893
  • 50
  • 121
  • 195

1 Answers1

2

for loops have the following structure:

for (<initialization>; <condition to keep running>; <iterative statements>)
    <loop body>

So, first step, you want to move the condition from your while loop statement into that middle section of the for loop statement.

for (something; (start = s.IndexOf('\n', start)) != -1; something;)

Now, we can introduce the initialization (int start = 0) to the first part and the iterative statement (start++) to the last part:

for (int start = 0; (start = s.IndexOf('\n', start)) != -1; start++)
{
    count++;
}

And there you have it.

itsme86
  • 19,266
  • 4
  • 41
  • 57
  • I think the whole point of moving to for was to get rid of the assignment in the conditional. – clcto May 25 '18 at 16:26
  • 1
    @clcto And how did you come to that conclusion? I don't see it mentioned anywhere by OP. – itsme86 May 25 '18 at 16:27
  • Because he moved it out of the conditional and it is a common style guideline to not do that. – clcto May 25 '18 at 16:27