简体   繁体   English

如何在C#中将字符串转换为字符串array []

[英]How to convert string to string array[] in c#

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 PS:如果有任何预定义的方法也有帮助

You can do that using Trim And Split : 您可以使用Trim And Split来做到这一点:

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

But your data looks like JSON string. 但是您的数据看起来像JSON字符串。 So, if you are dealing with JSON instead of making your own parser try using libraries that already does that such as JSON.NET . 因此,如果您使用的是JSON而不是使用自己的解析器,请尝试使用已经完成此操作的库,例如JSON.NET

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. 您可以使用Trim函数删除括号,然后使用Split()函数获取包含此字符串中由指定Unicode字符的元素分隔的子字符串的字符串数组。

var res  = output.TrimStart('[')
                 .TrimEnd(']')
                 .Split(',');
string[] arr = output.Where(c => Char.IsDigit(c)).Select(c => c.ToString()).ToArray();
output.Substring(1, output.Length - 2).Split(',');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM