C# 实现字符串文本换行的方法,文本如何换行
static void Main(string[] args)
{
Console.WriteLine(WrapText("HelloWord", 2));
Console.Read();
}
/// <summary>
/// 字符串文本换行
/// <para>
/// eg:WrapText("HelloWord", 2);==>"He\r\nll\r\noW\r\nord"
/// </para>
/// </summary>
/// <param name="input">传入文本</param>
/// <param name="width">每行宽度, 每多少字符换行</param>
/// <returns></returns>
public static string WrapText(string input, int width)
{
// 获取字符串长度
int length = input.Length;
StringBuilder sb = new StringBuilder(input);
if (width > 0 && length > width)
{
// 计算需要阻断字符长度
int breakLength = sb.Length / width;
for (int i = 0; i < breakLength; i++)
{
// 计算插入位置
int insertPosition = i * width;
if (insertPosition != 0)
{
int offset = (i - 1) * 2;
sb.Insert(insertPosition + offset, Environment.NewLine);
}
}
}
return sb.ToString();
}