kkkk00999
kkkk00999

Reputation: 179

Convert an escaped string to an String Array

I have this kind of String

string input="[\"Modell\",\"Jan.\",\"Feb.\",\"Mrz.\",\"Apr.\",\"Mai\",\"Jun.\",\"Jul.\",\"Aug.\",\"Sep.\",\"Okt.\",\"Nov.\",\"Dez.\"]";

I need to convert it into something like this:

string[] output;//convert "input" to it

I was looking at here,here and here, but it didn't help me.

How can I convert my string to string[] is this case ?

Upvotes: 0

Views: 505

Answers (3)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

What about this:

var output = input.Trim(new[] { '[', ']' }).Split(',').Select(x => x.Trim('\"')).ToArray();

Although this might work for your example I recommend using the approach given by @Cuong Le using Json-Deserializer. It is much more robust and also handles nested structures.

Upvotes: -1

IRAndreas
IRAndreas

Reputation: 441

Not very nice, but works:

string[] output = input.Replace("[", "").Replace("\"", "").Replace("]", "").Split(',').ToArray<string>();

Upvotes: -1

cuongle
cuongle

Reputation: 75326

Your input has json format as array of string, so you can simply use the very popular library Newtonsoft.Json on nuget, and then deserialize back to array of string in C#:

var result = JsonConvert.DeserializeObject<string[]>(input);

Upvotes: 8

Related Questions