Splitting a string into chunks of a certain size

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

    Six years later o_O

    Just because

        public static IEnumerable Split(this string str, int chunkSize, bool remainingInFront)
        {
            var count = (int) Math.Ceiling(str.Length/(double) chunkSize);
            Func start = index => remainingInFront ? str.Length - (count - index)*chunkSize : index*chunkSize;
            Func end = index => Math.Min(str.Length - Math.Max(start(index), 0), Math.Min(start(index) + chunkSize - Math.Max(start(index), 0), chunkSize));
            return Enumerable.Range(0, count).Select(i => str.Substring(Math.Max(start(i), 0),end(i)));
        }
    

    or

        private static Func start = (remainingInFront, length, count, index, size) =>
            remainingInFront ? length - (count - index) * size : index * size;
    
        private static Func end = (remainingInFront, length, count, index, size, start) =>
            Math.Min(length - Math.Max(start, 0), Math.Min(start + size - Math.Max(start, 0), size));
    
        public static IEnumerable Split(this string str, int chunkSize, bool remainingInFront)
        {
            var count = (int)Math.Ceiling(str.Length / (double)chunkSize);
            return Enumerable.Range(0, count).Select(i => str.Substring(
                Math.Max(start(remainingInFront, str.Length, count, i, chunkSize), 0),
                end(remainingInFront, str.Length, count, i, chunkSize, start(remainingInFront, str.Length, count, i, chunkSize))
            ));
        }
    

    AFAIK all edge cases are handled.

    Console.WriteLine(string.Join(" ", "abc".Split(2, false))); // ab c
    Console.WriteLine(string.Join(" ", "abc".Split(2, true))); // a bc
    Console.WriteLine(string.Join(" ", "a".Split(2, true))); // a
    Console.WriteLine(string.Join(" ", "a".Split(2, false))); // a
    

提交回复
热议问题