Splitting a string into chunks of a certain size

后端 未结 30 1595
时光说笑
时光说笑 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:24
    static IEnumerable<string> Split(string str, int chunkSize)
    {
       IEnumerable<string> retVal = Enumerable.Range(0, str.Length / chunkSize)
            .Select(i => str.Substring(i * chunkSize, chunkSize))
    
       if (str.Length % chunkSize > 0)
            retVal = retVal.Append(str.Substring(str.Length / chunkSize * chunkSize, str.Length % chunkSize));
    
       return retVal;
    }
    

    It correctly handles input string length not divisible by chunkSize.

    Please note that additional code might be required to gracefully handle edge cases (null or empty input string, chunkSize == 0).

    0 讨论(0)
  • 2020-11-22 08:24

    Personally I prefer my solution :-)

    It handles:

    • String lengths that are a multiple of the chunk size.
    • String lengths that are NOT a multiple of the chunk size.
    • String lengths that are smaller than the chunk size.
    • NULL and empty strings (throws an exception).
    • Chunk sizes smaller than 1 (throws an exception).

    It is implemented as a extension method, and it calculates the number of chunks is going to generate beforehand. It checks the last chunk because in case the text length is not a multiple it needs to be shorter. Clean, short, easy to understand... and works!

        public static string[] Split(this string value, int chunkSize)
        {
            if (string.IsNullOrEmpty(value)) throw new ArgumentException("The string cannot be null.");
            if (chunkSize < 1) throw new ArgumentException("The chunk size should be equal or greater than one.");
    
            int remainder;
            int divResult = Math.DivRem(value.Length, chunkSize, out remainder);
    
            int numberOfChunks = remainder > 0 ? divResult + 1 : divResult;
            var result = new string[numberOfChunks];
    
            int i = 0;
            while (i < numberOfChunks - 1)
            {
                result[i] = value.Substring(i * chunkSize, chunkSize);
                i++;
            }
    
            int lastChunkSize = remainder > 0 ? remainder : chunkSize;
            result[i] = value.Substring(i * chunkSize, lastChunkSize);
    
            return result;
        }
    
    0 讨论(0)
  • 2020-11-22 08:26
    static IEnumerable<string> 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<string> 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));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:26
    List<string> SplitString(int chunk, string input)
    {
        List<string> list = new List<string>();
        int cycles = input.Length / chunk;
    
        if (input.Length % chunk != 0)
            cycles++;
    
        for (int i = 0; i < cycles; i++)
        {
            try
            {
                list.Add(input.Substring(i * chunk, chunk));
            }
            catch
            {
                list.Add(input.Substring(i * chunk));
            }
        }
        return list;
    }
    
    0 讨论(0)
  • 2020-11-22 08:26
        public static List<string> SplitByMaxLength(this string str)
        {
            List<string> splitString = new List<string>();
    
            for (int index = 0; index < str.Length; index += MaxLength)
            {
                splitString.Add(str.Substring(index, Math.Min(MaxLength, str.Length - index)));
            }
    
            return splitString;
        }
    
    0 讨论(0)
  • 2020-11-22 08:27

    Simple and short:

    // this means match a space or not a space (anything) up to 4 characters
    var lines = Regex.Matches(str, @"[\s\S]{0,4}").Cast<Match>().Select(x => x.Value);
    
    0 讨论(0)
提交回复
热议问题