Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actionscript 3.0 String With Format?

Tags:

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.

like image 283
Chunky Chunk Avatar asked Feb 19 '10 20:02

Chunky Chunk


2 Answers

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.

like image 146
Jordan Running Avatar answered Sep 28 '22 06:09

Jordan Running


Casting objects to strings

The method toString() is defined on the Object class. So all objects have this method defined for them. Calling myObject.toString() will therefore usually give you what you're looking for. Certain objects define additional methods, such as date.getHours(), which return string descriptions of the object in a different format from that supplied by getString().

For native types such as int, you can cast using String(myInt).

Concatenating strings together

You can then add together the different parts of a string as follows:

var myString:String = "There are " + String(24) + " hours in a day." 

Hope that helps, Dave

like image 34
Dave T Avatar answered Sep 28 '22 07:09

Dave T