简体   繁体   中英

How to convert a string containing an array into a list<ushort> ?

For example there is a string str = "[2,3,4,5]" How to convert this array of type string into a list where I can get each element in the list of type ushort? The string gets the value "[2,3,4,5]" from ruby script.

使用linq可以做到

var numbers = str.Where(y=>Char.IsDigit(y)).Select(p=>UInt16.Parse(p.ToString())).ToArray();

It's actually quite simple. All you need to do is write a method that parses the string and splits it up. Here is an basic example with NO error checking or optimizations. The naming convention is purely for your understanding purposes.

List <ushort> ConvertToUShortList (string arrayText)
{
    var result = new List<ushort> ();
    var bracketsRemoved = arrayText.Replace ("[", "").Replace ("]", "");
    var numbersSplit = bracketsRemoved.Split ( new string[] {","}, System.StringSplitOptions.None);

    foreach (var number in numbersSplit)
    {
        result.Add (ushort.Parse (number));
    }

    return result;
}

I shouldn't need to explain anything in this method due to the names I have given things. If you don't understand anything, let me know and I'll clarify it for you.

Another method (more checks):

class Program
{
    static void Main(string[] args)
    {
        var str = "[1,2,3,4,5,6,7,8,9]";

        var x = FromRubyArray(str);

        Console.WriteLine(str);
        Console.WriteLine(string.Join("-", x));
        Console.ReadLine();
    }

    public static List<ushort> FromRubyArray(string stra)
    {
        if (string.IsNullOrWhiteSpace(stra)) return new List<ushort>();
        stra = stra.Trim();
        stra = stra.Trim('[', ']');

        return stra                
            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(s => Convert.ToUInt16(s))
            .ToList();
    }
}

Since this string is using a "Json-like" format, you can use this code:

JavaScriptSerializer serializer = new JavaScriptSerializer();
var array = serializer.Deserialize<ushort[]>("[2,3,4,5]");

You just need to reference the System.Web.Extensions assembly

使用Newtonsoft的Json.net( http://www.newtonsoft.com/json )的另一种优雅方式

            var ushortArray = JsonConvert.DeserializeObject<List<ushort>>(myString);

You could do something like

List<ushort> myUshorts = new List<ushort>("[200,3,4,5]".Trim('[', ']').Split(',').Select(ushort.Parse));

if you know that's exactly how the output will be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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