Lost A Life Gaming
Lost A Life Gaming

Reputation: 15

How to take a string, split it into an array and then join it back together

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

Answers (1)

Thomas Weller
Thomas Weller

Reputation: 59303

I love using LinqPad for such tasks, because you can use Console.WriteLine() to get the details of a result like so:

LinqPad

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:

LinqPad Result

Upvotes: 2

Related Questions