Splitting a string into chunks of a certain size

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

    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;
        }
    

提交回复
热议问题