This article illustrates the different techniques to split a string into chunks of equal size in C#. Each chunk except the last one should be of the same size. The last chunk may be of a smaller length, consisting of the remaining characters.

1. Using String.Substring() method

The idea is to extract each chunk using the String.Substring(int, int) method to partition the string into fixed-size chunks. For example, the following code split a string into two equal-length substrings:

Download  Run Code

 
The above code will work only for strings that can be split into an equal number of chunks and throw ArgumentOutOfRangeException exception otherwise. You can easily extend the code to make it work with strings of any length, as demonstrated below. Note that the last chunk will be smaller.

Download  Run Code

2. Using Chunk() method

Starting with .NET 6, you can use the Enumerable.Chunk() method to split a string into chunks of specified size. It returns an IEnumerable<T> that contains elements of the input sequence split into chunks of specified size. The last chunk can be smaller than the specified size and will contain the remaining elements.

Download  Run Code

That’s all about splitting a string into chunks of equal size in C#.