This is slightly complicated by the fact that we have to handle "
", "
" AND "
". I'm assuming you don't need to handle "
" - if you do, you'll have to add a case for it in the code below.
Obviously there are many ways to solve this; here's a low-level approach that doesn't use anything other than a basic loop:
public static IEnumerable<string> SplitByAndKeepLineSeparators(string input)
{
if (input.Length == 0)
yield break;
int i = 0, j = 0;
while (true)
{
if (i == input.Length - 1) // Last char?
{
yield return input.Substring(j, i - j + 1);
break;
}
switch (input[i])
{
case '
' when input[i+1] == '
':
yield return input.Substring(j, i - j + 2);
i += 2;
j = i;
break;
case '
':
yield return input.Substring(j, i - j + 1);
j = ++i;
break;
case '
':
yield return input.Substring(j, i - j + 1);
j = ++i;
break;
default:
++i;
break;
}
}
}
Note: If using an older version of C# you won't be able to use that kind of switch
, so your code would have to be:
public static IEnumerable<string> SplitByAndKeepLineSeparators(string input)
{
if (input.Length == 0)
yield break;
int i = 0, j = 0;
while (true)
{
if (i == input.Length - 1) // Last char?
{
yield return input.Substring(j, i - j + 1);
break;
}
if (input[i] == '
' && input[i + 1] == '
')
{
yield return input.Substring(j, i - j + 2);
i += 2;
j = i;
}
else if (input[i] == '
')
{
yield return input.Substring(j, i - j + 1);
j = ++i;
}
else if (input[i] == '
')
{
yield return input.Substring(j, i - j + 1);
j = ++i;
}
else
{
++i;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…