Transforming string to array?

575 views
Skip to first unread message

Mandemon

unread,
Aug 26, 2013, 7:32:28 AM8/26/13
to haxe...@googlegroups.com
I have a XML file from which I read data. Within data, there is an array which is saved, for example:

<node array="[1, 2, 3]" />

Now, I read this data into string and I get "[1, 2, 3]", but as you might guess, I want to turn this into an array. Is there a ready function for this or is there some other trick to do? I tried looking over API, but I found no solution (Or I am too blind  to realize it).

TL;DR version:

Is anything like

var text:String = "[1, 2, 3]";
var array:Array<Int> = text.ToArray();

Luca

unread,
Aug 26, 2013, 7:42:30 AM8/26/13
to haxe...@googlegroups.com
var array = text.substr(1,text.length-2).split(",").map(Std.parseInt)

Mandemon

unread,
Aug 26, 2013, 8:02:16 AM8/26/13
to haxe...@googlegroups.com
Thanks! It works. Can I ask detailed answer what ti exactly does? Just so that I know what I am doing. I personally don't like "Black boxes" in my code. I figured it first creates a substring by removing [ and ], then splits it into arrays based on , sign, but the last one eludes me.

Juraj Kirchheim

unread,
Aug 26, 2013, 8:13:40 AM8/26/13
to haxe...@googlegroups.com
Also `var array:Array<Int> = haxe.Json.parse(text);` happens to work
in this case.

As for map, see the documentation here: http://api.haxe.org/Array.html#map

It creates a new array by applying Std.parseInt to each of the elements.

Regards,
Juraj

j...@justinfront.net

unread,
Aug 26, 2013, 8:20:23 AM8/26/13
to haxe...@googlegroups.com
Juraj

Very smart, I guess performance with Json it will be very platform dependant ( ie does it use native if so it will be fast ).

Mandemon

I was just explain the map thing when saw Juraj post, it may still be useful.

map is just applying a function to each element in the array and putting it in a new array.  In this case we are using a static function. The function you are applying is Std.parseInt. So you can expand the operation out to maybe feel clearer on how map works..

var newStructure = myArrayOfString.map( function( item: String ):Int{  // do something to each item and return the Int result } );

but basically you just need to understand map.

Haxe is smart because it is inferring the new structure as Array<Int>

--
To post to this group haxe...@googlegroups.com
http://groups.google.com/group/haxelang?hl=en
---
You received this message because you are subscribed to the Google Groups "Haxe" group.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages