Efficiently Splitting Strings into Custom-Sized Chunks in C#
This article demonstrates a C# method for dividing a string into smaller, equally sized segments. Imagine you have a long string:
<code class="language-csharp">string longString = "1111222233334444";</code>
And you need to break it into chunks of a specific length, say 4 characters each. The desired output would be:
<code>"1111" "2222" "3333" "4444"</code>
The Solution: A Clean and Concise Approach
The most efficient way to achieve this is using LINQ's Enumerable.Range
and Select
methods:
<code class="language-csharp">static IEnumerable<string> ChunkifyString(string str, int chunkSize) { if (string.IsNullOrEmpty(str) || chunkSize <= 0) { yield break; // Handle null, empty, or invalid chunk size } for (int i = 0; i < str.Length; i += chunkSize) { yield return str.Substring(i, Math.Min(chunkSize, str.Length - i)); } }</code>
This improved method uses a for
loop and yield return
for better performance, especially with very large strings. It also explicitly handles null or empty input strings and non-positive chunk sizes, making it more robust. The Math.Min
function ensures that the last chunk doesn't exceed the string's remaining length.
Usage Example:
<code class="language-csharp">string myString = "111122223333444455"; int chunkSize = 4; foreach (string chunk in ChunkifyString(myString, chunkSize)) { Console.WriteLine(chunk); }</code>
This will output:
<code>1111 2222 3333 4444 55</code>
This approach elegantly handles strings whose lengths are not perfectly divisible by the chunk size, ensuring all characters are included in the resulting chunks. This solution is both concise and efficient, making it ideal for various string manipulation tasks.
The above is the detailed content of How Can I Chunkify a String into Custom-Sized Segments in C#?. For more information, please follow other related articles on the PHP Chinese website!