This post will discuss how to split a string into chunks of a certain size in C#. For example, splitting a string AAAAABBBBBCCCCC into chunks of size 5 will result into substrings [AAAAA, BBBBB, CCCCC].

1. Using LINQ

We can use LINQ’s Select() method to split a string into substrings of equal size. The following code example shows how to implement this:

Download  Run Code

2. Using String.Substring() method

Another solution is to simply use the String.Substring() method to break the string into substrings of the given size, as shown below:

Download  Run Code

 
The above code will throw an exception when the string length is not a multiple of the given size. The following code example shows how to handle this:

Download  Run Code

3. Using Regex

We can write a regular expression to split a string into substrings of equal size. Here’s the regex one-liner version using LINQ:

Download  Run Code

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