質問

I was just discovering the Roslyn source code and I saw a code snippet looks like this:

var text = stringBuilder.ToString();
int length;
do
{
    length = text.Length;
    text = text.Replace("{\r\n\r\n", "{\r\n");
} while (text.Length != length);

It looks odd to me because the String.Replace method, replaces all the occurrences of specified string with a new value in one time.So this loop is executing for first time, perform the changes then executing again for second time and do nothing. Then it ends.. So what is the point of using a loop instead of just write:

var text =  stringBuilder.ToString();
text = text.Replace("{\r\n\r\n", "{\r\n");

Or even shorter:

var text = stringBuilder.ToString().Replace("{\r\n\r\n", "{\r\n");

Am I missing something ?

役に立ちましたか?

解決

Suppose the string has three blank lines after an open brace:

"{\r\n\r\n\r\n\r\n"

The first iteration would produce this:

"{\r\n\r\n\r\n"

The second would produce this:

"{\r\n\r\n"

And the third would produce:

"{\r\n"

Each iteration removes a single blank line.

他のヒント

Yes - you're missing that the string could contain more than two linebreaks after the bracket "{" - it would then continue to delete the additional linebreaks until only one remains.

It's using recursion (of a sort) to handle one set of replacements exposing a new set characters that subsequently need replacing in the same way.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top