How to Split String in Equal Parts: C#

October 13, 2013 , , 0 Comments

String is a text of Unicode characters in any programming language, it can be changeable as the user want. Splitting a string means to divide a string in an array after performing some operations on it. These operation may be to remove desired character, blank spaces or find out a substring of a particular length.

A string can be split into chunks of equal size, given by the user. Create two string variable, first will contains the original string that is to be split, second string is empty and will contain the split string.

Write the following code in which for loop is used to get our desired chunk size. I am dividing the string in chunks of 4.
string stringToDivide = "abcdefghijklmnopqrstuvwxyz";
string stringAfterDivide = string.Empty;
int part = 4;
int stringLength = stringToDivide.Length;
for (int i = 0; i < stringLength; i += part)
if (i + part > stringLength) part = stringLength - i;
stringAfterDivide += stringToDivide.Substring(i, part) + " ";

I am using alphabets as original string, and at the last the string will be divide in chunk of four as shown in below message box.

How to split string in equal parts in windows forms C#

The string can be changed according to the user’s requirements, or may be input by the user through the textbox. The chunk size can also be changed, or may also be input by the user. 

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google