Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

specified splitting of string

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading