Split string in 512 char chunks

后端 未结 8 1673
我在风中等你
我在风中等你 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:32

    I will dare to provide a more LINQified version of Jon's solution, based on the fact that the string type implements IEnumerable<char>:

    private IList<string> SplitIntoChunks(string text, int chunkSize)
    {
        var chunks = new List<string>();
        int offset = 0;
        while(offset < text.Length) {
            chunks.Add(new string(text.Skip(offset).Take(chunkSize).ToArray()));
            offset += chunkSize;
        }
        return chunks;
    }
    
    0 讨论(0)
  • 2021-02-06 00:33
    static IEnumerable<string> Split(string str, int chunkSize)    
    {   
        int len = str.Length;
        return Enumerable.Range(0, len / chunkSize).Select(i => str.Substring(i * chunkSize, chunkSize));    
    }
    

    source: Splitting a string into chunks of a certain size

    0 讨论(0)
提交回复
热议问题