Split string in 512 char chunks

后端 未结 8 1670
我在风中等你
我在风中等你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 00:19

    using Jon's implementation and the yield keyword.

    IEnumerable Chunks(string text, int chunkSize)
    {
        for (int offset = 0; offset < text.Length; offset += chunkSize)
        {
            int size = Math.Min(chunkSize, text.Length - offset);
            yield return text.Substring(offset, size);
        }
    }
    

提交回复
热议问题