简体   繁体   English

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

[英]How do I split a text into different values?

I want to split the inputted data then check each line so if it's a number it gets pushed into the score Array and if not then it gets pushed into the name Array. 我想拆分输入的数据,然后检查每一行,以便如果它是数字,则将其压入得分数组,如果不是,则将其压入名称Array。 I'm new and I have no idea what I'm doing. 我是新手,我不知道自己在做什么。 so far I have this : 到目前为止,我有这个:

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());

I recommend you to use regular expressions. 我建议您使用正则表达式。

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

Does this suit your needs? 这符合您的需求吗?

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
}

Then you can sort it or whatever you intend to do with it. 然后,您可以对其进行排序,也可以对其进行任何处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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