我的意思是,这是一种快速的方法。
它不使用昂贵的正则表达式函数。它也不使用多个替换函数,每个替换函数都通过多次检查、分配等对数据进行循环。
所以搜索直接在一个for
循环中完成。对于必须增加结果数组容量的次数,Array.Copy
函数内也使用了循环。这就是所有的循环。在某些情况下,更大的页面大小可能更有效。
public static string NormalizeNewLine(this string val)
{
if (string.IsNullOrEmpty(val))
return val;
const int page = 6;
int a = page;
int j = 0;
int len = val.Length;
char[] res = new char[len];
for (int i = 0; i < len; i++)
{
char ch = val[i];
if (ch == '\r')
{
int ni = i + 1;
if (ni < len && val[ni] == '\n')
{
res[j++] = '\r';
res[j++] = '\n';
i++;
}
else
{
if (a == page) // Ensure capacity
{
char[] nres = new char[res.Length + page];
Array.Copy(res, 0, nres, 0, res.Length);
res = nres;
a = 0;
}
res[j++] = '\r';
res[j++] = '\n';
a++;
}
}
else if (ch == '\n')
{
int ni = i + 1;
if (ni < len && val[ni] == '\r')
{
res[j++] = '\r';
res[j++] = '\n';
i++;
}
else
{
if (a == page) // Ensure capacity
{
char[] nres = new char[res.Length + page];
Array.Copy(res, 0, nres, 0, res.Length);
res = nres;
a = 0;
}
res[j++] = '\r';
res[j++] = '\n';
a++;
}
}
else
{
res[j++] = ch;
}
}
return new string(res, 0, j);
}
我现在 '\n\r' 实际上并没有在基本平台上使用。但是谁会连续使用两种换行符来表示两个换行符呢?
如果你想知道,那么你需要先看看 \n 和 \r 是否在同一个文档中分别使用。