C#换行每n个字符 [英] C# line break every n characters

查看:569
本文介绍了C#换行每n个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有文本的字符串:THIS IS A TEST。我如何分割每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.

任何帮助将不胜感激。

推荐答案

让我们从我的答案代码审查。每个 字符插入一个换行符:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆