How can i format a string with supplied variables in AS3?
//vars
var myNumber:Number = 12;
var myString:String = "Months";
var myObject:MovieClip = year;
//string
myString.txt = "One (?) consists of (?) consecutive (?)", string(myObject), string(myNumber), myString;
so in the string above, i would like myString to display "One year consists of 12 consecutive Months", but i'm new to AS3 and do not know how to properly format a string.
i'm sure that i'll have to cast the number variable into a string, string(myNumber), but i don't know if casting a movie clip variable to a string, string(myMovieClip), will return the name of the movie clip or produce an error. i'm willing to bet on the later.
The answers to this similar question suggest using the Formatter class or StringUtil.substitute().
The latter looks the simplest; in your case you would use it like this:
var str:String = "One {0} consists of {1} consecutive {2}";
var newString:String = StringUtil.substitute(str, myObject, myNumber, myString);
substitute()
should automatically cast its arguments to String, but I'm not sure if, as in your code, you can cast a MovieClip (myObject
) as a String.
Another good option, especially if you've used printf
in other programming languages, is this third-party printf-as3 function.