haxe

Haxe: How do I repeat a string n times


I want to repeat a character or string, such as "Z", a specific number of times (let's say 5 times). I could easily do it in a loop, of course, like this:

var combined = "";
for(i in 0...5) {
    combined += "Z";
}
trace(combined); // ZZZZZ

But is there a function in the standard library, or a some kind of special syntax sugar, that would allow me to do it as a one liner?


Solution

  • There are a couple of ways it could be done in a one-liner.

    1. From the standard library, you could call StringTools.rpad() or StringTools.lpad(), starting with an empty string (it only works if the second argument is length 1, though):
    var combined = StringTools.rpad("", "Z", 5);
    
    1. You could use Array comprehension to add the character to an array n times, and then call Array.join() with an empty string as the separator:
    var combined = [for (i in 0...5) "Z"].join("");