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 ?

1
  • Is that a JSON input, or some format of your own? There's plenty of JSON deserialization libraries around. Commented Mar 31, 2016 at 9:00

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

-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.

2 Comments

Won't remove the [ and ], won't solve the problem with substrings containing the ", like string input="[\"Mod\\\"ell\"]"
I changed it to 'input.Split(',').Select(x => x.Trim('\"')).ToArray<string>();' 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..
-1

Not very nice, but works:

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

3 Comments

"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 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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.