假设我有一个文本为"THIS IS A TEST“的字符串。我如何每隔n个字符拆分它?因此,如果n是10,那么它将显示:
"THIS IS A "
"TEST"
..you明白我的意思了。原因是我想把一行很长的行分成更小的行,就像换行一样。我想我可以使用string.Split()来做这件事,但是我不知道怎么做,我很困惑。
任何帮助都将不胜感激。
发布于 2011-10-14 13:39:13
让我们借用my answer在代码审查方面的实现。这将每隔n个字符插入一个换行符:
public static string SpliceText(string text, int lineLength) {
return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
}
编辑:
要返回字符串数组,请执行以下操作:
public static string[] SpliceText(string text, int lineLength) {
return Regex.Matches(text, ".{1," + lineLength + "}").Cast<Match>().Select(m => m.Value).ToArray();
}
发布于 2011-10-14 13:48:25
也许这可以用来有效地处理极大的文件:
public IEnumerable<string> GetChunks(this string sourceString, int chunkLength)
{
using(var sr = new StringReader(sourceString))
{
var buffer = new char[chunkLength];
int read;
while((read= sr.Read(buffer, 0, chunkLength)) == chunkLength)
{
yield return new string(buffer, 0, read);
}
}
}
实际上,这适用于任何TextReader
。StreamReader
是最常用的TextReader
。您可以处理非常大的文本文件(IIS日志文件、SharePoint日志文件等),而不必加载整个文件,而是逐行读取。
发布于 2011-10-14 13:38:18
为此,您应该能够使用正则表达式。下面是一个示例:
//in this case n = 10 - adjust as needed
List<string> groups = (from Match m in Regex.Matches(str, ".{1,10}")
select m.Value).ToList();
string newString = String.Join(Environment.NewLine, lst.ToArray());
有关详细信息,请参阅此问题:
https://stackoverflow.com/questions/7768373
复制相似问题