Reputation: 2999
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.
Upvotes: 0
Views: 1817
Reputation: 4069
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);
Upvotes: 1
Reputation: 101742
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);
Upvotes: 0