0

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 ?

Community
  • 1
  • 1
kkkk00999
  • 179
  • 2
  • 13
  • Is that a JSON input, or some format of your own? There's plenty of JSON deserialization libraries around. – Luaan Mar 31 '16 at 09:00

3 Answers3

8

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);
cuongle
  • 74,024
  • 28
  • 151
  • 206
-1

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.

cuongle
  • 74,024
  • 28
  • 151
  • 206
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • 3
    Won't remove the `[` and `]`, won't solve the problem with substrings containing the `"`, like `string input="[\"Mod\\\"ell\"]"` – xanatos Mar 31 '16 at 08:36
  • I changed it to 'input.Split(',').Select(x => x.Trim('\"')).ToArray();' but I get ' [0]: "[\"Modell" [1]: "Jan." [2]: "Feb." [3]: "Mrz." [4]: "Apr." [5]: "Mai" [6]: "Jun." [7]: "Jul." [8]: "Aug." [9]: "Sep." [10]: "Okt." [11]: "Nov." [12]: "Dez.\"]"' actually "Dez" and "Modell" have a backslash too much.. – kkkk00999 Mar 31 '16 at 08:39
-1

Not very nice, but works:

string[] output = input.Replace("[", "").Replace("\"", "").Replace("]", "").Split(',').ToArray<string>();
IRAndreas
  • 401
  • 1
  • 3
  • 9
  • "works" - for this specific example. The input is JSON, and for that you simply use a JSON parsing library. The input may contain commas, quotes and nested arrays as well. – CodeCaster Mar 31 '16 at 08:42
  • @CodeCaster The input *looks* like JSON, and may be JSON. But unless it's JSON by contract, that assumption is kind of dangerous. I've dealt with so many "XML-like" formats in the past that I really don't like those kinds of assumptions anymore :D It's just way too likely that the input is produced by mindlessly slapping strings together, just like it used to be done with INI, CSV, XML or even HTTP before. – Luaan Mar 31 '16 at 09:03
  • @Luaan questions as vague as this should not be answered in the first place. Assuming it is _not_ JSON and writing your own parser is at least as dangerous. – CodeCaster Mar 31 '16 at 09:06