-1

i have a string variable which receives data from web the data is in the from of string like this

string output="[1,2,3,4,5,6,7,8,9,0]";

i want to convert it into a string array [] so that i can specify each element via for each loop

string output;
into
string[] out;

PS: if any predefined method is there that will also help

sudo
  • 906
  • 2
  • 14
  • 32

4 Answers4

7

You can do that using Trim And Split:

var out = output.TrimStart('[').TrimEnd(']').Split(',');

But your data looks like JSON string. So, if you are dealing with JSON instead of making your own parser try using libraries that already does that such as JSON.NET.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • yes i am dealing with json but array can also work as JSON is in array [] not as a object {} – sudo Jan 18 '15 at 14:02
4

You can use Trim functions to remove brackets and then use Split() function to get the string array that contains the substrings in this string that are delimited by elements of a specified Unicode character.

var res  = output.TrimStart('[')
                 .TrimEnd(']')
                 .Split(',');
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
2
string[] arr = output.Where(c => Char.IsDigit(c)).Select(c => c.ToString()).ToArray();
w.b
  • 11,026
  • 5
  • 30
  • 49
1
output.Substring(1, output.Length - 2).Split(',');
Kapol
  • 6,383
  • 3
  • 21
  • 46