Home > Enterprise >  specified splitting of string
specified splitting of string

Time:12-13

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

CodePudding user response:

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.

CodePudding user response:

This could be a viable solution if you don't mind using Lists:

string str = "[A]     [C]     [E] [F]";
List<string> test = new List<string>();
int index = 0;
bool looping = true;

do
{
    test.Add(str.Substring(index, 3));

    str = str.Remove(0, 3);

    if (str.Count() > 0)
        str = str.Remove(0, 1);
    else if (str.Count() == 0)
        looping = false;
} while (looping);

foreach (var substr in test)
{
    Console.WriteLine(substr);
}
  •  Tags:  
  • c#
  • Related