将string.Split(',')转换为int数组

时间:2011-07-20 13:51:28

标签: arrays string actionscript-3 split

我有以下字符串:

"2,26,17,33,6,14,9,29,1"

一系列intusedIds

如果我这样做:

private var usedIds:Array;
usedIds = "2,26,17,33,6,14,9,29,1".split(',');

我得到一个strings数组。

如何才能获得int的数组?

4 个答案:

答案 0 :(得分:5)

最简单的方法是使用Linq:

int[] usedIds = "2,26,17,33,6,14,9,29,1".split(',').Select(x => int.Parse(x)).ToArray();

答案 1 :(得分:2)

你可以试试这个:

package 
{
    import flash.display.Sprite;
    import flash.events.Event;

    public class Main extends Sprite 
    {
        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);

        }// end function

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            var string:String = "2,26,17,33,6,14,9,29,1";

            var strings:Array = string.split(',');

            var ints:Array = new Array();

            for each(var s:String in strings)
            {
                ints.push(int(s));

            }// end for each

            trace(ints[0]) // output: 2
            trace(ints[0] is int) // output: true

        }// end function

    }// end class

}// end package

<强> [UPDATE]

以上版本的略短版本是:

var string:String = "2,26,17,33,6,14,9,29,1";

var ints:Array = new Array();

for each(var s:String in string.split(","))
{
    ints.push(int(s));

}// end for each

trace(ints[0]) // output: 2
trace(ints[0] is int) // output: true

[更新2]

最短(不推荐):

var ints:Array = [];

for each(var s:String in "2,26,17,33,6,14,9,29,1".split(",")) ints.push(int(s));

trace(ints[0]) // output: 2
trace(ints[0] is int) // output: true

答案 2 :(得分:2)

另一个例子:

var a:Array = "2,26,17,33,6,14,9,29,1".split(",");
a.forEach(function(item:*, index:int, array:Array):void{
   array[index] = int(item);
});

答案 3 :(得分:1)

您可能需要遍历数组并进行转换(测试):

function splitToInt($input:String,$delimiter:String):Array
{
    var inArr:Array = $input.split($delimiter);
    var outArr:Array = [];
    for each(var index in inArr) {
        trace(index);
        outArr.push(int(index));
    }
    return outArr;  
}

var usedIds:Array = splitToInt("2,26,17,33,6,14,9,29,1",",");