在512字符块分割字符串 [英] Split string in 512 char chunks
本文介绍了在512字符块分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
也许一个基本的问题,但让我们说我有一个字符串,它是2000个字符长,我需要拆分此字符串到每个最多512字符块。
Maybe a basic question but let us say I have a string that is 2000 characters long, I need to split this string into max 512 character chunks each.
时有一个很好的方式,就像一个循环或因此这样做
Is there a nice way, like a loop or so for doing this?
推荐答案
事情是这样的:
private IList<string> SplitIntoChunks(string text, int chunkSize)
{
List<string> chunks = new List<string>();
int offset = 0;
while (offset < text.Length)
{
int size = Math.Min(chunkSize, text.Length - offset);
chunks.Add(text.Substring(offset, size));
offset += size;
}
return chunks;
}
或只是遍历:
private IEnumerable<string> SplitIntoChunks(string text, int chunkSize)
{
int offset = 0;
while (offset < text.Length)
{
int size = Math.Min(chunkSize, text.Length - offset);
yield return text.Substring(offset, size);
offset += size;
}
}
请注意,这个分裂成UTF-16代码块单位,这是不一样分裂成的Unicode码分块,而这又可能不一样分裂成字形的块相当的相同。
Note that this splits into chunks of UTF-16 code units, which isn't quite the same as splitting into chunks of Unicode code points, which in turn may not be the same as splitting into chunks of glyphs.
这篇关于在512字符块分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文