Repeat a string: Difference between revisions
Content added Content deleted
No edit summary |
(Added an ActionScript version.) |
||
Line 3: | Line 3: | ||
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). |
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). |
||
=={{header|ActionScript}}== |
|||
ActionScript does not have a built-in way to repeat a string multiple times, but the addition operator can be used to concatenate strings. |
|||
===Iterative version=== |
|||
<lang ActionScript>function repeatString(string:String, numTimes:uint):String |
|||
{ |
|||
var output:String = ""; |
|||
for(var i:uint = 0; i < numTimes; i++) |
|||
output += string; |
|||
return output; |
|||
}</lang> |
|||
===Recursive version=== |
|||
The following double-and-add method is much faster when repeating a string many times. |
|||
<lang ActionScript>function repeatRecursive(string:String, numTimes:uint):String |
|||
{ |
|||
if(numTimes == 0) return ""; |
|||
if(numTimes & 1) return string + repeatRecursive(string, numTimes - 1); |
|||
var tmp:String = repeatRecursive(string, numTimes/2); |
|||
return tmp + tmp; |
|||
}</lang> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
In [[Ada]] multiplication of an universal integer to string gives the desired result. Here is an example of use: |
In [[Ada]] multiplication of an universal integer to string gives the desired result. Here is an example of use: |