假设我有一个包含文本"THIS IS A TEST"的字符串。我该如何在每n个字符处分割它?例如,如果n为10,则应显示:
"THIS IS A "
"TEST"
..你们明白我的意思。原因是我希望将一行很长的文本拆分成较小的文本行,有点像自动换行的功能。我认为可以使用string.Split()来实现,但我不知道如何操作,感到困惑。
谢谢任何帮助。
假设我有一个包含文本"THIS IS A TEST"的字符串。我该如何在每n个字符处分割它?例如,如果n为10,则应显示:
"THIS IS A "
"TEST"
..你们明白我的意思。原因是我希望将一行很长的文本拆分成较小的文本行,有点像自动换行的功能。我认为可以使用string.Split()来实现,但我不知道如何操作,感到困惑。
谢谢任何帮助。
我们可以借鉴代码评审中我的答案的实现方法。这个方法可以在每个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();
}
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日志文件等),而无需加载整个文件,而是逐行读取。
source.Length
不是 chunkLength
的倍数,这种方法是否会漏掉最后的字符? - Jack Millerwhile ((read = sr.Read(buffer, 0, chunkLength)) !=0)
。 - 我零0七您应该能够使用正则表达式来完成此操作。以下是一个示例:
//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());
请参考此问题以获取详细信息:
将字符串分成相同大小的块
也许不是最优的方式,但是不需要使用正则表达式:
string test = "my awesome line of text which will be split every n characters";
int nInterval = 10;
string res = String.Concat(test.Select((c, i) => i > 0 && (i % nInterval) == 0 ? c.ToString() + Environment.NewLine : c.ToString()));
String.Concat()
而不是使用空字符串连接。 - Jeff Mercado在进行代码审查后回到这里,还有另一种方法可以不使用 Regex
来实现相同的功能。
public static IEnumerable<string> SplitText(string text, int length)
{
for (int i = 0; i < text.Length; i += length)
{
yield return text.Substring(i, Math.Min(length, text.Length - i));
}
}
我刚写的一些代码:
string[] SplitByLength(string line, int len, int IsB64=0) {
int i;
if (IsB64 == 1) {
// Only Allow Base64 Line Lengths without '=' padding
int mod64 = (len % 4);
if (mod64 != 0) {
len = len + (4 - mod64);
}
}
int parts = line.Length / len;
int frac = line.Length % len;
int extra = 0;
if (frac != 0) {
extra = 1;
}
string[] oline = new string[parts + extra];
for(i=0; i < parts; i++) {
oline[i] = line.Substring(0, len);
line = line.Substring(len);
}
if (extra == 1) {
oline[i] = line;
}
return oline;
}
string CRSplitByLength(string line, int len, int IsB64 = 0)
{
string[] lines = SplitByLength(line, len, IsB64);
return string.Join(System.Environment.NewLine, lines);
}
string m = "1234567890abcdefghijklmnopqrstuvwxhyz";
string[] r = SplitByLength(m, 6, 0);
foreach (string item in r) {
Console.WriteLine("{0}", item);
}