String Functions in ActionScript
ActionScript doesn’t have a direct equivalent to the strings
package in Go, but we can create similar functionality using built-in String methods and custom functions. Here’s how we can replicate the string operations in ActionScript:
package {
import flash.display.Sprite;
import flash.text.TextField;
public class StringFunctions extends Sprite {
public function StringFunctions() {
var output:TextField = new TextField();
output.width = 400;
output.height = 300;
addChild(output);
function p(...args):void {
output.appendText(args.join(" ") + "\n");
}
// Here's a sample of string functions in ActionScript
p("Contains: ", "test".indexOf("es") != -1);
p("Count: ", countOccurrences("test", "t"));
p("HasPrefix: ", "test".indexOf("te") == 0);
p("HasSuffix: ", "test".lastIndexOf("st") == "test".length - 2);
p("Index: ", "test".indexOf("e"));
p("Join: ", ["a", "b"].join("-"));
p("Repeat: ", repeatString("a", 5));
p("Replace: ", "foo".replace(/o/g, "0"));
p("Replace: ", "foo".replace("o", "0"));
p("Split: ", "a-b-c-d-e".split("-"));
p("ToLower: ", "TEST".toLowerCase());
p("ToUpper: ", "test".toUpperCase());
}
private function countOccurrences(str:String, substr:String):int {
return str.split(substr).length - 1;
}
private function repeatString(str:String, count:int):String {
var result:String = "";
for (var i:int = 0; i < count; i++) {
result += str;
}
return result;
}
}
}
This ActionScript code demonstrates various string operations similar to those in the original example. Here’s an explanation of the functions:
contains
: We useindexOf
to check if a substring exists.count
: We implement a customcountOccurrences
function.hasPrefix
andhasSuffix
: We useindexOf
andlastIndexOf
respectively.index
: ActionScript’sindexOf
works similarly.join
: ActionScript has a built-injoin
method for arrays.repeat
: We implement a customrepeatString
function.replace
: ActionScript’sreplace
method can use regex for global replacement or a simple string for single replacement.split
: ActionScript has a built-insplit
method.toLower
andtoUpper
: ActionScript hastoLowerCase
andtoUpperCase
methods.
To run this ActionScript code, you would typically compile it into a SWF file and run it in a Flash Player or AIR runtime environment. The output would be displayed in a TextField on the stage.
Note that ActionScript is typically used in the context of Flash or AIR applications, so the setup and execution are quite different from command-line programs. The output in this case would be visible in the application window rather than printed to a console.