HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Split a String by an indexes array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraysplitstringindexes

Problem

Let's say I have a plain text string that I want to split into a string array, using an integer array containing the indexes of this string where I want it to be cut.

Example:

Input string: "001ABCD2T"

Indexes array: {3, 7, 8}

Expected resulting string array: {"001", "ABCD", "2", "T"}

Here's how I do it for now:

string line = "001ABCD2T";
int[] markers = new int[] {3, 7, 8};

for (int i = -1; i < markers.Length; i++)
{
    string value = String.Empty;
    if (i == -1)
        value = line.Substring(0, markers[0]);
    else if (i == markers.Length - 1)
        value = line.Substring(markers[i], line.Length - markers[i]);
    else
        value = line.Substring(markers[i], markers[i + 1] - markers[i]);

    Console.WriteLine(value);
}


The result is as expected, yet it is pretty eye-soring. Is there a cleaner way to write it, or even better, an already implemented method I didn't find?

Solution

Disclaimer: I'm not actually very familiar with C#. I'll also refrain from the style review and let someone more familiar with common practices take a crack.

You can prepend 0 and append line.Length to your array, simplifying the logic. There's probably a better way, but I got it working with a List:

List list = new List();
list.Add(0);
list.AddRange(markers);
list.Add(line.Length);

for (int i = 0; i < list.Count - 1; i++)
{
    string value = line.Substring(list[i], list[i + 1] - list[i]);
    Console.WriteLine(value);
}

Code Snippets

List<int> list = new List<int>();
list.Add(0);
list.AddRange(markers);
list.Add(line.Length);

for (int i = 0; i < list.Count - 1; i++)
{
    string value = line.Substring(list[i], list[i + 1] - list[i]);
    Console.WriteLine(value);
}

Context

StackExchange Code Review Q#61852, answer score: 10

Revisions (0)

No revisions yet.