I needed to convert a string representing an array , like :
var a:String = "[u,[[a,b],[l,m,r,a,f,g,h],[u]],[c,q],d]"
into a real Array, so I started looking in forums, but I couldn’t find it, so I wrote my own ArrayString class.
Now I can use the following code:
var a:String = "[u,[[a,b],[l,m,r,a,f,g,h],[u]],[c,q],d]"
var u:ArrayString = new ArrayString(a)
var r:Array = u.array
trace(r.length.toString())
...
Here is the code of my ArrayString Class (attached as file), maybe you can use it…
package jojaspi
{
import mx.controls.Alert;
public class ArrayString
{
private var globGroupOpen:String
private var globGroupClose: String
private var globDelimiter: String
//properties
public var string:String
public var array:Array
//constructor
public function ArrayString(str:String,GroupOpen:String="[",GroupClose:String="]",
delimiter:String =",") {
this.globGroupOpen = GroupOpen
this.globGroupClose = GroupClose
this.globDelimiter = delimiter
this.string = str
try {
var err:Error = IsArrayString(str)
if (err!=null) {
throw err
this.array = null
} else {
this.array = DoTheSplitting(str)
}
}
catch (err:Error) {
Alert.show(err.message +"
Couldn't split string into Array","Error in \""+this.string+"\"")
throw err
}
}
//=================================================================================
public function IsArrayString(str:String,splitterArray:Array = null) : Error {
var grouping:int =0
var strOrg: String = str
if ((str.substr(0,1) != this.globGroupOpen) || (str.slice(-1) != this.globGroupClose)) {
return new Error('No opening "' + this.globGroupOpen + '" and/or closing "' + this.globGroupClose + '"')
}
str = str.slice(1,-1)
for (var i:int = 0;i<str.length;i++) {
switch (str.substr(i,1)) {
case '"':
i = str.indexOf('"',i+1)
if (i==-1) return new Error('Cannot find closing "...')
break;
case "'":
i = str.indexOf("'",i+1)
if (i==-1) return new Error("Cannot find closing '...")
break;
case this.globGroupOpen:
grouping++
break;
case this.globGroupClose:
grouping--
break;
case this.globDelimiter:
if (grouping == 0) {
if (splitterArray != null) {
splitterArray.push(i)
}
}
break;
default:
}
if (grouping < 0) {
return new Error(this.globGroupOpen + " and " + this.globGroupClose + ' in wrong order or total string not enclosed in "' + this.globGroupOpen + '" and "' + this.globGroupClose + '"');
}
}
if (grouping > 0) {
return new Error('Too little ' + this.globGroupClose + "'s")
}
return null
}
private function DoTheSplitting (str:String):* {
var tmpArray: Array = new Array
var splitterArray:Array = new Array
if (IsArrayString(str,splitterArray)==null) {
var j:int=0
for (var i:int = 0;i<splitterArray.length;i++) {
//slice and push
tmpArray.push(str.slice(1,-1).substring(j,splitterArray*))
j=splitterArray*+1
}
tmpArray.push(str.slice(1,-1).substring(j)) //last element
return tmpArray.map(arguments.callee) as Array
} else {
return str as String
}
}
}
}