Reputation: 15
I have some code that will take in a string from console in [0,0,0,0] format. I then want to split it into an array but leave the [] and only take the numbers. How do i do this? This is what i have, i thought i could split it all and remove the brackets after but it doesnt seem to take the brackets and rather just leaves a null space. is there a way to split from index 1 to -1?
input = Console.ReadLine();
Char[] splitChars = {'[',',',']'};
List<string> splitString = new List<string>(input.Split(splitChars));
Console.WriteLine("[" + String.Join(",", splitString) + "]");
Console.ReadKey();
Upvotes: 1
Views: 243
Reputation: 59303
I love using LinqPad for such tasks, because you can use Console.WriteLine()
to get the details of a result like so:
It becomes obvious that you have empty entries, i.e. ""
at the beginning and the end. You want to remove those with the overloaded funtion that takes StringSplitOptions.RemoveEmptyEntries
[MSDN]:
List<string> splitString = new List<string>(input.Split(splitChars, StringSplitOptions.RemoveEmptyEntries));
Result:
Upvotes: 2