public static string WordWrap(string input, int wrapAt)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (wrapAt <= 0)
throw new ArgumentOutOfRangeException(nameof(wrapAt), "Wrap length must be greater than zero.");
StringBuilder wrappedString = new StringBuilder();
int inputLength = input.Length;
int currentLineLength = 0;
for (int i = 0; i < inputLength; i++)
{
if (currentLineLength == wrapAt)
{
wrappedString.Append("\n");
currentLineLength = 0;
}
wrappedString.Append(input[i]);
currentLineLength++;
// If we're at the end of the input string and the current line isn't full,
// append a newline character if necessary.
if (i == inputLength - 1 && currentLineLength < wrapAt)
{
wrappedString.Append("\n");
}
}
return wrappedString.ToString();
}
c#字符串 input 长度超过参数 wrapat 时 自动折行
于 2024-03-13 16:01:23 首次发布