C#换行每n个字符

ray*_*ran 7 c# split character line

假设我有一个带有文本的字符串:"这是一个测试".我怎么会每n个字符拆分一次?所以如果n是10,那么它会显示:

"THIS IS A "
"TEST"
Run Code Online (Sandbox Code Playgroud)

你明白了.原因是因为我想将一条非常大的线分成更小的线,有点像自动换行.我想我可以使用string.Split(),但我不知道如何和我感到困惑.

任何帮助,将不胜感激.

Guf*_*ffa 19

让我们从代码审查的答案中借用一个实现.这会每n个字符插入一个换行符:

public static string SpliceText(string text, int lineLength) {
  return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
}
Run Code Online (Sandbox Code Playgroud)

编辑:
返回一个字符串数组:

public static string[] SpliceText(string text, int lineLength) {
  return Regex.Matches(text, ".{1," + lineLength + "}").Cast<Match>().Select(m => m.Value).ToArray();
}
Run Code Online (Sandbox Code Playgroud)