0

How i can split the json string in Unity? I have a string called entry_text, which is passed by a function. When I print it out. It is

"Atmosphere\t7\nGravity\t\nMagnetism\t\nSeismic Activity\t\nSurface\t\nTemperature\t\nWeather\t\nElement 1\t\nElement 2\t\nElement 3\t\n7",

which contains "\t", and "\n". So i want to split the string by "\t" and "\n".

I used the

 string[] lines = entry_text.Split(new string[] {"\n"}, StringSplitOptions.None);

I also tried

string[] lines = Regex.Split(entry_text, "\n");

This also does not work:

string[] lines = entry_text.Split(new Char[] {'\n'}, StringSplitOptions.None);

It seems that the split function does not take "\n" as Enter or "\t" as space from Json.

4
  • what do you mean by it doesn't work, exactly ? did you get wrong results ? what is your expected result ? Commented Mar 30, 2014 at 23:55
  • Does your string have a literal \n newline in it, or a ` character followed by a n` character? If the latter, have you tried \\n instead of \n? Commented Mar 31, 2014 at 0:36
  • Hi, @Selman22...i mean it did not really split it. because when i print lines.Length, it is still 1, also the lines[0] is just the full string... Commented Mar 31, 2014 at 1:57
  • Side note: I don't see any JSON in the sample... Could you please clarify why you mention JSON in the post? (I've removed some extra text from your post - feel free to revert my changes if you feel there was something important except hi/thanks text) Commented Mar 31, 2014 at 2:04

2 Answers 2

1

If you have this as your string:

string entry_text = "Atmosphere\t7\nGravity\t\nMagnetism\t\nSeismic Activity\t\nSurface\t\nTemperature\t\nWeather\t\nElement 1\t\nElement 2\t\nElement 3\t\n7";

Remember that the \t and \n in the string are two separate characters: a \ followed by either a t or n.

When you define:

string[] lines = entry_text.Split(new string[] {"\n"}, StringSplitOptions.None);

Your {"\n"} is being translated into a newline character, not two separate characters. For that, you will want to escape the \ character in \n:

string[] lines = entry_text.Split(new string[] {"\\n"}, StringSplitOptions.None);

An alternate way of writing this is to use the @ symbol, which means "take the literal characters in this string, instead of escaping them":

string[] lines = entry_text.Split(new string[] {@"\n"}, StringSplitOptions.None);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use multiple delimiters:

string[] lines = entry_text.Split('\t', '\n');

If you want to Split by new-line character you can also try this:

string[] lines = entry_text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

Comments

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.