Is there a way to do the following:
string str = "[A] [C] [E] [F]";
and then splitting the string down to a collection looking like:
List<string> myList = {"[A]", " ", "[C]", " ", "[E]", "[F]"}
In text: Is there a way to split the string by taking 3, then skipping 1. There is no ending space. Otherwise the following had worked fine: https://stackoverflow.com/a/1450797/14375615
I can’t just add 1 to length, that just caused an error because the last item wasn’t 4 chars long
>Solution :
I’d try different approach than method indicated in the other question. It’s more straight forwardly handling the last segment if its length is smaller than chunkSize:
static IEnumerable<string> Split(string str, int chunkSize, int gapSize)
{
var index = 0;
while (index < str.Length - chunkSize - 1)
{
yield return str.Substring(index, chunkSize);
index += chunkSize + gapSize;
}
if (str.Length - index > 0)
{
yield return str.Substring(index, str.Length - index);
}
}
Then usage:
Split(str, 3, 1)
will produce desired result.