我有一个包含换行符的字符串,并且我想包装这些单词。我想保留换行符,以便在显示文本时看起来像单独的段落。有人有很好的功能吗?下面的当前函数和代码(不是我自己的函数)。 WordWrap函数似乎正在剥离\ n个字符。
root.countries.title
答案 0 :(得分:0)
如果您希望换行符使文本看起来像段落,只需使用String对象的Replace方法。
var str =
"Line 1\n" +
"Line 2\n" +
"Line 3\n";
Console.WriteLine("Before:\n" + str);
str = str.Replace("\n", "\n\n");
Console.WriteLine("After:\n" + str);
答案 1 :(得分:0)
这里是自动换行功能,它通过使用正则表达式来查找可以打破的地方和必须打破的地方。然后,它基于“中断区域”返回原始文本。它甚至允许在连字符(和其他字符)处中断而不删除连字符(因为正则表达式使用零宽度的正向超前断言)。
new <- new[new$id %in% unique(df1$id),]
答案 2 :(得分:0)
最近,我一直在创建一些抽象,这些抽象在性能和内存敏感的控制台上下文中模仿类似于窗口的功能。
为此,我必须实现自动换行功能,而没有任何不必要的字符串分配。
以下是我设法简化成的内容。此方法:
Microsoft.Extensions.Primitives.StringSegment
结构实例返回行的起始索引和长度(但是用您自己的结构替换该结构,或直接附加到StringBuilder
上非常简单)。public static IEnumerable<StringSegment> WordWrap(string input, int maxLineLength, char[] breakableCharacters)
{
int lastBreakIndex = 0;
while (true)
{
var nextForcedLineBreak = lastBreakIndex + maxLineLength;
// If the remainder is shorter than the allowed line-length, return the remainder. Short-circuits instantly for strings shorter than line-length.
if (nextForcedLineBreak >= input.Length)
{
yield return new StringSegment(input, lastBreakIndex, input.Length - lastBreakIndex);
yield break;
}
// If there are native new lines before the next forced break position, use the last native new line as the starting position of our next line.
int nativeNewlineIndex = input.LastIndexOf(Environment.NewLine, nextForcedLineBreak, maxLineLength);
if (nativeNewlineIndex > -1)
{
nextForcedLineBreak = nativeNewlineIndex + Environment.NewLine.Length + maxLineLength;
}
// Find the last breakable point preceding the next forced break position (and include the breakable character, which might be a hypen).
var nextBreakIndex = input.LastIndexOfAny(breakableCharacters, nextForcedLineBreak, maxLineLength) + 1;
// If there is no breakable point, which means a word is longer than line length, force-break it.
if (nextBreakIndex == 0)
{
nextBreakIndex = nextForcedLineBreak;
}
yield return new StringSegment(input, lastBreakIndex, nextBreakIndex - lastBreakIndex);
lastBreakIndex = nextBreakIndex;
}
}