2015-12-12 56 views
0

在AS3代码中,是否有可能检查字符串中的第一个单词是什么?如果它是特定单词,请执行某些操作?检查字符串中的第一个单词是什么

例:

var str:String = mySharedObject.data.theDate; //monday 21 january 2015 

if (first word of str is "monday" or "apple"){ 
Do that 
}else{ 
Do that instead 
} 

THX

回答

1

要做到这一点,您可以:

  • 1)找到的第一个空间的索引和存储。

  • 2)从0开始提取一个子串,找到上面找到的索引(如果需要,可以存储它)。

  • 3)将子串与条件进行比较并继续。

所以,你的代码可以是这样的,例如:

var str:String = 'hello world, world hello'; 
var i:int = str.indexOf(' '); 
var first_word:String = str.substr(0, i); 

if(first_word == 'hello' || first_word == 'world') 
{ 
    // ... 
} 
else 
{ 
    // ... 
} 
+0

+1,因为'String.indexOf()+ String.substr()'比'String.split()'快。我还添加了一个例子。 – akmozo

1

您可以使用该String.Split函数字符串分解为字符串数组:

var str:String = "monday 21 january 2015" ; // mySharedObject.data.theDate; 

    // Split the string into an array of 'words' using RegEx 
    var wordArray:Array = str.split(/\W+/g); 

    //if (first word of str is "monday" or "apple"){ 
    if (wordArray[0] == "monday" || wordArray[0] == "apple") { 
     trace("do that"); 
    } else { 
     trace("do that instead") 
    } 
相关问题