如何将文本拆分为不同的值?

时间:2015-04-17 16:33:04

标签: arrays actionscript-3

我想分割输入的数据,然后检查每一行,如果它是一个数字,它会被推入得分数组,如果不是,那么它会被推入名称数组。我是新人,我不知道我在做什么。到目前为止我有这个:

var lines:Array = String(event.target.data).split(":");

var linesNum:int = lines.length;
for(var i:int = 0 ; i < linesNum; i++){
  trace('line ' + i + ': ' + lines[i]);

var scores:Array = []; 

for (var i:int; i < lines.length; i++) {
  scores.push(lines[i]);
}
classone_import.text = (scores.sort());

2 个答案:

答案 0 :(得分:1)

我建议你使用正则表达式。

var str:String = "*Test B:10 *Test A:0 *Test C:7";

var wordsRe:RegExp = /\w+ \w+/g; // word + space + word
var valuesRe:RegExp = /\d+/g; // only digits

var names:Array = str.match(wordsRe);
var scores:Array = str.match(valuesRe);

trace(names);//Test B, Test A, Test C
trace(scores);//10, 0, 7

答案 1 :(得分:0)

这是否符合您的需求?

var s:String = "*Test B:10 *Test A:0 *Test C:7";
var divider:String = "*"; //the divider is "*" - taken from your example
var arr:Array = s.split(divider); //split the string by the specified divider

var scores:Array = [];
var names:Array = [];

for(var i:int=0; i<arr.length; i++) {
    if(arr[i] == "") continue; //I am not sure whether this will occur but as your string begins with *, the first item may be "" -> so skip that
    var item:Array = arr[i].split(":"); //split the string to 'name', 'score'
    names.push(item[0]);
    scores.push(parseFloat(item[1])); //parse the number from string; you could use parseInt if all the numbers are integers for sure
}

然后你可以对它或任何你打算用它做的事情进行排序。