Split string in 512 char chunks

后端 未结 8 1679
我在风中等你
我在风中等你 2021-02-05 23:47

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,

8条回答
  •  时光说笑
    2021-02-06 00:18

    Something like this:

    private IList SplitIntoChunks(string text, int chunkSize)
    {
        List chunks = new List();
        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;
    }
    

    Or just to iterate over:

    private IEnumerable 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;
        }
    }
    

    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.

提交回复
热议问题