Reputation: 1195
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.
Upvotes: 0
Views: 1371
Reputation: 3047
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);
Upvotes: 1
Reputation: 5474
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);
Upvotes: 0
Reputation: 415715
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;
Upvotes: 9
Reputation: 8551
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.)
Upvotes: 2