Splitting a string into chunks of a certain size

后端 未结 30 1603
时光说笑
时光说笑 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:01

    I know question is years old, but here is a Rx implementation. It handles the length % chunkSize != 0 problem out of the box:

       public static IEnumerable Chunkify(this string input, int size)
            {
                if(size < 1)
                    throw new ArgumentException("size must be greater than 0");
    
                return input.ToCharArray()
                    .ToObservable()
                    .Buffer(size)            
                    .Select(x => new string(x.ToArray()))
                    .ToEnumerable();
            }
    

提交回复
热议问题