0

I have a unique situation where I need to create string arrays that have null in position zero and then a split string for the remaining positions. For example, I want to input the following string:

"this/\is/\a/\test/\string"

to output the following results

array[0] = null;
array[1] = "this";
array[2] = "is";
array[3] = "a";
array[4] = "test";
array[5] = "string";

I know I can accomplish this in a clunky way with a number of lines of code, but I'm looking for an elegant way to split a string to a specific array position, or just to insert null before it. An empty string for position 0 would also be acceptable but not ideal. Is there a good way to accomplish this? The number of array positions will vary, as the input string will have varying numbers of parameters I need to pull.

1
  • 2
    Split it the way you'd do normally, use Array.Copy and copy it to index 1 and set index 0 to null. Commented Jun 11, 2014 at 14:04

4 Answers 4

9

Prepend your delimiter to the string and then set the first element to null after the split:

string data = @"this/\is/\a/\test/\string";
string[] result = (@"/\" + data).Split(new[] {@"/\"}, StringSplitOptions.None);
result[0] = null;
Sign up to request clarification or add additional context in comments.

Comments

2

I suppose you could prepend a "/\" to the string you're about to split...

(This would give you an empty string rather than null, which you say is okay but not ideal. If you want to make the first entry null, you could do that after the fact.)

Comments

1

If you need to do this many times and you want your code to look clean - or perhaps you want a variable number of prepended nulls, you could always write up your own extension method:

public static class Extensions
{
    public static string[] Split(this string input, string delimiter, int prependNullCount)
    {
        var defaultSplit = input.Split(new string[] { delimiter }, StringSplitOptions.None);

        string[] result = new string[defaultSplit.Length + prependNullCount];

        defaultSplit.CopyTo(result, prependNullCount);

        return result;
    }
}

and then you would use the method as:

string input = @"this/\is/\a/\test/\string";
string[] result = input.Split(@"/\", 1);

Comments

0

you can add /\ at the first index and the split by "/\ Simple code :

string input = @"this/\is/\a/\test/\string";
string[] result = (@"/\" + input ).Split(new[] {@"/\"}, StringSplitOptions.None);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.