Skip to content

Instantly share code, notes, and snippets.

@evanportwood
Forked from booyaa/CSharpChunkaString.md
Created July 25, 2017 22:37
Show Gist options
  • Save evanportwood/aaa05d0ace5eb2d14cb009be44508017 to your computer and use it in GitHub Desktop.
Save evanportwood/aaa05d0ace5eb2d14cb009be44508017 to your computer and use it in GitHub Desktop.
C# Chunk a String

#split string into an array of strings

source: http://stackoverflow.com/a/3008775/105282

namespace StringChunks
{
    static class Tools
    {
        public static IEnumerable<string> SplitByLength(this string str, int maxLength)
        {
            for (int index = 0; index < str.Length; index += maxLength)
            {
                yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
            }
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            string bigText = String.Concat(Enumerable.Repeat("helloworld", 1024*1024)); // 1MB
            string[] bigTextChunked = Tools.SplitByLength(bigText, 32768).ToArray();
            Console.WriteLine("bigText is {0} bytes\nbigTextChunked has {1} elements\nbigTextChunked [0] is {2} bytes", bigText.Length, bigTextChunked.Length, bigTextChunked[0].Length);
        }
    }
}    

output:

bigText is 10485760 bytes
bigTextChunked has 320 elements
bigTextChunked [0] is 32768 bytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment