Identifying individual values in a text box using Flash
I want to identify specific strings in a text box from user input to add to a score variable, like so -
if (userWords.text == firstWord) { score = score + 1; }
The example given adds 1 to the score, but if a user adds a space then a second word the text box views it as a whole and not individual words, resulting in no values added to the score variable.
The problem lies with the whole text box being viewe开发者_如何学Cd as one entire string. Instead, I want to split it up so word1 will add 1 to the score, word2 will add 1 to the score, etc.
I am ultra confused with this problem, so thank you to anyone that may help.
You can use the trim() method of the StringHelper class. This will removes all characters that match the char parameter before and after the specified string. You can find the class in the example at the bottom of the String class page on Adobe livedocs. The url is http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/String.html but its also as follows:
class StringHelper {
public function StringHelper() {
}
public function replace(str:String, oldSubStr:String, newSubStr:String):String {
return str.split(oldSubStr).join(newSubStr);
}
public function trim(str:String, char:String):String {
return trimBack(trimFront(str, char), char);
}
public function trimFront(str:String, char:String):String {
char = stringToCharacter(char);
if (str.charAt(0) == char) {
str = trimFront(str.substring(1), char);
}
return str;
}
public function trimBack(str:String, char:String):String {
char = stringToCharacter(char);
if (str.charAt(str.length - 1) == char) {
str = trimBack(str.substring(0, str.length - 1), char);
}
return str;
}
public function stringToCharacter(str:String):String {
if (str.length == 1) {
return str;
}
return str.slice(0, 1);
}
}
Then you can implement it as follows:
var strHelper:StringHelper = new StringHelper();
if (strHelper.trim(userWords.text, " ") == firstWord) { score = score + 1; }
To make life easier(especially if your using the timeline), you can simply extract the required methods from the StringHelper class and add it to your code. This way you can call the functions without the need of instantiating the StringHelper class and calling it from its instance. The following is an example of this:
function trim(str:String, char:String):String {
return trimBack(trimFront(str, char), char);
}
function trimFront(str:String, char:String):String {
char = stringToCharacter(char);
if (str.charAt(0) == char) {
str = trimFront(str.substring(1), char);
}
return str;
}
function trimBack(str:String, char:String):String {
char = stringToCharacter(char);
if (str.charAt(str.length - 1) == char) {
str = trimBack(str.substring(0, str.length - 1), char);
}
return str;
}
function stringToCharacter(str:String):String {
if (str.length == 1) {
return str;
}
return str.slice(0, 1);
}
if (trim(userWords.text, " ") == firstWord) { score = score + 1; };
精彩评论