Monday, February 18, 2013

Function to Split String in Chunks of Given Max Size

Friends,

Following is the function to split a given string in chunks of given maximum size:

 public static List SplitString(string stringToSplit, int maxLength)
        {
            List lstStr = new List();

            if (!String.IsNullOrEmpty(stringToSplit) && maxLength > 0 && stringToSplit.Length - maxLength >= 0)
            {
                int count = 0;
                for (int i = 0; i < stringToSplit.Length; )
                {
                    count = stringToSplit.Length - i >= maxLength ? maxLength : stringToSplit.Length - i;
                    lstStr.Add(stringToSplit.Substring(i, count));
                    i = i + maxLength;
                }
            }

            return lstStr;
        }