There are several ways to do this, the idea is usually to go through the string and each n characters get block with method String.Substring() passing as parameter the initial position and the size of the current block, and finally adding it in a array.
The version using for of function SplitBlocks of maniero’s response:
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 in 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 in Ideone.
With the method Enumerable.Range 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, result that will be the amount of pieces obtained from the text.
On the next line is the .Select which is used to select each piece and apply an action on it, the .Skip is used to ignore a certain amount of characters and the .Take is used to recover certain amount of characters.
Note: It is necessary to include 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.
To anchor \G is used to say that the match should start at the position where the previous match ended, the point (.) is used to capture any character, and finally, the {12} is used to delimit the amount of characters we want to return.
Note: It is necessary to include the namespace System.Text.RegularExpressions.
@Marconi No. This string will change with each repeat. What I need is to separate this data every 12 characters.
– Randrade