Hello.
Maybe a basic question but lets say I have a string that is 2000 characters long, I need to split this string into max 512 character chunks each.
Is there a nice way, eg. a loop for doing this?
Thank you :-)
Hello.
Maybe a basic question but lets say I have a string that is 2000 characters long, I need to split this string into max 512 character chunks each.
Is there a nice way, eg. a loop for doing this?
Thank you :-)
Something like this:
private IList<string> SplitIntoChunks(string text, int chunkSize)
{
List<string> chunks = new List<string>();
int offset = 0;
while (offset < text.Length)
{
int size = Math.Min(chunkSize, text.Length - offset);
chunks.Add(text.Substring(offset, size));
offset += size;
}
return chunks;
}
Or just to iterate over:
private IEnumerable<string> SplitIntoChunks(string text, int chunkSize)
{
int offset = 0;
while (offset < text.Length)
{
int size = Math.Min(chunkSize, text.Length - offset);
yield return text.Substring(offset, size);
offset += size;
}
}
static IEnumerable<string> Split(string str, int chunkSize)
{
int len = str.Length;
return Enumerable.Range(0, len / chunkSize).Select(i => str.Substring(i * chunkSize, chunkSize));
}
source: http://stackoverflow.com/questions/1450774/c-split-a-string-into-equal-chunks-each-of-size-4
Something like?
Calculate eachLength = StringLength / WantedCharLength
Then for (int i = 0; i < StringLength; i += eachLength)
SubString (i, eachLength);
I will dare to provide a more LINQified version of Jon's solution, based on the fact that the string
type implements IEnumerable<char>
:
private IList<string> SplitIntoChunks(string text, int chunkSize)
{
var chunks = new List<string>();
int offset = 0;
while(offset < text.Length) {
chunks.Add(new string(text.Skip(offset).Take(chunkSize).ToArray()));
offset += chunkSize;
}
return chunks;
}
using Jon's implementation and the yield keyword.
IEnumerable<string> Chunks(string strText, int chunkSize)
{
for (int offset = 0; offset < text.Length; offset += size)
{
int size = Math.Min(chunkSize, text.Length - offset);
yield return text.Substring(offset, size);
}
yield break;
}
Though this question meanwhile has an accepted answer, here's a short version with the help of regular expressions. Purists may not like it (understandably) but when you need a quick solution and you are handy with regexes, this can be it. Performance is rather good, surprisingly:
string [] split = Regex.Split(yourString, @"(?<=\G.{512})");
What it does? Negative look-backward and remembering the last position with \G
. It will also catch the last bit, even if it isn't dividable by 512.