Split a string into chunks of equal size in C#
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Collections.Generic; public static class StringExtensions { public static IEnumerable<string> Partition(this string input, int partitionSize) { for (int i = 0; i < input.Length; i += partitionSize) { yield return input.Substring(i, partitionSize); } } } public class Example { public static void Main() { string s = "ABCDEFGH"; var tokens = s.Partition(2); Console.WriteLine(String.Join(", ", tokens)); // AB, CD, EF, GH } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Collections.Generic; public static class StringExtensions { public static IEnumerable<string> Partition(this string input, int partitionSize) { for (int i = 0; i < input.Length; i += partitionSize) { yield return input.Substring(i, Math.Min(partitionSize, input.Length - i)); } } } public class Example { public static void Main() { string s = "ABCDEFG"; var tokens = s.Partition(3); Console.WriteLine(String.Join(", ", tokens)); // ABC, DEF, G } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { string s = "ABCDEFG"; List<String> tokens = s.Chunk(3) .Select(s => new string(s)) .ToList(); Console.WriteLine(String.Join(", ", tokens)); // ABC, DEF, G } } |
That’s all about splitting a string into chunks of equal size in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)