Splitting a string into chunks of a certain size

后端 未结 30 1639
时光说笑
时光说笑 2020-11-22 07:55

Suppose I had a string:

string str = \"1111222233334444\"; 

How can I break this string into chunks of some size?

e.g., breaking t

30条回答
  •  太阳男子
    2020-11-22 08:26

    static IEnumerable Split(string str, double chunkSize)
    {
        return Enumerable.Range(0, (int) Math.Ceiling(str.Length/chunkSize))
           .Select(i => new string(str
               .Skip(i * (int)chunkSize)
               .Take((int)chunkSize)
               .ToArray()));
    }
    

    and another approach:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class Program
    {
        public static void Main()
        {
    
            var x = "Hello World";
            foreach(var i in x.ChunkString(2)) Console.WriteLine(i);
        }
    }
    
    public static class Ext{
        public static IEnumerable ChunkString(this string val, int chunkSize){
            return val.Select((x,i) => new {Index = i, Value = x})
                      .GroupBy(x => x.Index/chunkSize, x => x.Value)
                      .Select(x => string.Join("",x));
        }
    }
    

提交回复
热议问题