当前接受的答案过于复杂,不确定是否准确(见评论)。一个更简单和准确的解决方案是:
public static class StringExtensions
{
public static string BreakLongLine(this string line, int maxLen, string newLineCharacter)
{
// if there is nothing to be split, return early
if (line.Length <= maxLen)
{
return line;
}
StringBuilder lineSplit = new StringBuilder();
var words = line.Split(' ');
var charCount = 0;
for (var i = 0; i < words.Length; i++)
{
if (charCount + words[i].Length >= maxLen)
{
// '>=' and not '>' because I need to add an extra character (space) before the word
// and last word character should not be cut
lineSplit.Append(newLineCharacter);
charCount = 0;
}
if (charCount > 0)
{
lineSplit.Append(' ');
charCount++;
}
lineSplit.Append(words[i]);
charCount += words[i].Length;
}
return lineSplit.ToString();
}
}
请注意,此解决方案:
- 不要在行尾留空格;
- 代码更干净。例如,具有更少的条件并且它会提前返回以提高代码准备度
我还用单元测试介绍了这个方法,所以你可以看到它是有效的:
public class StringExtensionsTests
{
[Fact]
public void SplitIntoTwoLines()
{
// arrange
const string longString = "Four words two lines";
// act
var resultString = longString.BreakLongLine(10, "\n");
// assert
Assert.Equal("Four words\ntwo lines", resultString);
}
[Fact]
public void SplitIntoThreeLines()
{
// arrange
const string longString = "Four words two lines";
// act
var resultString = longString.BreakLongLine(9, "\n");
// assert
Assert.Equal("Four\nwords two\nlines", resultString);
}
// https://stackoverflow.com/questions/15793409/how-to-split-a-string-into-multiple-lines-if-more-than-37-characters-are-present
[Fact]
public void StackOverflowExample()
{
// arrange
const string longString = "The Quick Brown Fox Jumped Over The Lazy Dog";
// act
var resultString = longString.BreakLongLine(37, "\n");
// assert
Assert.Equal("The Quick Brown Fox Jumped Over The\nLazy Dog", resultString);
}
}