C# 修改换行符
namespace System
{
using System;
using System.Text;
public class StringNewLine
{
/// <summary>
/// 修改换行符号。
/// </summary>
/// <param name="value"></param>
/// <param name="newLine"></param>
/// <returns></returns>
public static string ChangeNewLine(string value, string newLine)
{
// 控件同时按下 Shift + Enter 输入垂直制表 \v
// 类 Unix 系统换行。 "\n"
// Mac 系统换行。 "\r"
// Windows 系统换行。 "\r\n"
string newValue;
if (string.IsNullOrEmpty(value) || value.IndexOfAny(new char[] { '\v', '\r', '\n' }) < 0)
{
newValue = value;
}
else
{
var addedCapacity = 64;
var capacity = value.Length + Math.Min(addedCapacity, int.MaxValue - value.Length);
var builder = new StringBuilder(capacity);
for (int index = 0; index < value.Length; index++)
{
var ch = value[index];
switch (ch)
{
case '\v':
case '\r':
builder.Append(newLine);
break;
case '\n':
{
var indexBefore = index - 1;
if (indexBefore == -1 || value[indexBefore] != '\r')
{
builder.Append(newLine);
}
}
break;
default:
builder.Append(ch);
break;
}
}
newValue = builder.ToString();
}
return newValue;
}
}
}