Split string in 512 char chunks

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

    Generic extension method:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public static class IEnumerableExtensions
    {
      public static IEnumerable> SplitToChunks (this IEnumerable coll, int chunkSize)
      {
        int skipCount = 0;
        while (coll.Skip (skipCount).Take (chunkSize) is IEnumerable part && part.Any ())
        {
          skipCount += chunkSize;
          yield return part;
        }
      }
    }
    
    class Program
    {
      static void Main (string[] args)
      {
        var col = Enumerable.Range(1,1<<10);
        var chunks = col.SplitToChunks(8);
    
        foreach (var c in chunks.Take (200))
        {
          Console.WriteLine (string.Join (" ", c.Select (n => n.ToString ("X4"))));
        }
    
        Console.WriteLine ();
        Console.WriteLine ();
    
        "Split this text into parts that are fifteen characters in length, surrounding each part with single quotes and output each into the console on seperate lines."
          .SplitToChunks (15)
          .Select(p => $"'{string.Concat(p)}'")
          .ToList ()
          .ForEach (p => Console.WriteLine (p));
    
        Console.ReadLine ();
      }
    }
    

提交回复
热议问题