C# 每 n 个字符换行 [英] C# line break every n characters
本文介绍了C# 每 n 个字符换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个带有文本的字符串:这是一个测试".我将如何将它拆分为每 n 个字符?所以如果 n 是 10,那么它会显示:
Suppose I have a string with the text: "THIS IS A TEST". How would I split it every n characters? So if n was 10, then it would display:
"THIS IS A "
"TEST"
……你懂的.原因是因为我想将一个非常大的行分成更小的行,有点像自动换行.我想我可以为此使用 string.Split(),但我不知道如何使用,而且我很困惑.
..you get the idea. The reason is because I want to split a very big line into smaller lines, sort of like word wrap. I think I can use string.Split() for this, but I have no idea how and I'm confused.
任何帮助将不胜感激.
推荐答案
让我们从 我的答案 关于代码审查.这会每 n 个字符插入一个换行符:
Let's borrow an implementation from my answer on code review. This inserts a line break every n characters:
public static string SpliceText(string text, int lineLength) {
return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
}
改为返回字符串数组:
To return an array of strings instead:
public static string[] SpliceText(string text, int lineLength) {
return Regex.Matches(text, ".{1," + lineLength + "}").Cast<Match>().Select(m => m.Value).ToArray();
}
这篇关于C# 每 n 个字符换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文