There are several ways to do this, the idea is usually to go through the string and every n characters get the block with the String.Substring()
by passing the starting position and the size of the current block as a parameter, and finally adding it to an array .
The version using for
of the SplitBlocks
function of bigown answer :
static List<String> DividirBlocos(string texto, int blocos){
var partes = new List<String>();
int tamanho = texto.Length;
// Incrementa "i" conforme o valor de "blocos". 0, 12, 24, 36...
for (int i = 0; i < tamanho; i += blocos){
if (i + blocos > tamanho) blocos = tamanho - i;
partes.Add(texto.Substring(i, blocos));
}
return partes;
}
Functional example on Ideone .
Another alternative that can be used is through a query using LINQ :
static IEnumerable<string> DividirBlocos(string texto, double blocos){
return Enumerable.Range(0, (int)Math.Ceiling(texto.Length / blocos))
.Select(i => new string(texto
.Skip(i * (int)blocos)
.Take((int)blocos)
.ToArray()));
}
Functional example on Ideone .
With the method Enumerable.Range
you get a range of values, the Math.Ceiling
is used to round up the result of the division between the text size and the amount of blocks in>, this result being the quantity of pieces obtained from the text.
On the next line is .Select
that is used to select each piece and apply an action on it, .Skip
is used to ignore a certain amount of characters and .Take
is used to retrieve certain number of characters.
Note : You must include the namespaces System.Collections.Generic
and System.Linq
.
Another way to do this can also be through regular expressions :
List<string> partes = new List<string>(Regex.Split(texto, @"(?<=\G.{12})",
RegexOptions.Multiline));
Functional example in Ideone .
Regular expressions in this case should probably be the most inefficient, in addition to lower performance.
The anchor \G
is used to say that the match should begin at the position where the previous match ended, the dot ( .
) is used to catch any character, and finally, the {12}
is used to delimit the amount of characters we want to return. >
Note : You must include the namespace System.Text.RegularExpressions
.