Haxe中如何实现字符串重复拼接(类似Python的字符串乘法)
First off, you’re right that Haxe doesn’t support Python-style String * Int syntax directly — the * operator in Haxe only works with numeric types, which is why you’re getting that "String should be Int" compilation error. Let’s walk through the proper, efficient ways to achieve the string repetition you want:
1. Use the Built-in repeat Method (Recommended)
Haxe 4 and later include a native repeat method directly on the String class. This is the cleanest, most optimized approach:
class Test { static function main() { var a = "Text"; var b = 4; trace(a.repeat(b)); // Output: TextTextTextText } }
If you’re working with an older Haxe version (pre-4), use the StringTools.repeat utility function instead — just remember to import it first:
import haxe.StringTools; class Test { static function main() { var a = "Text"; var b = 4; trace(StringTools.repeat(a, b)); // Output: TextTextTextText } }
2. Optimized Loop with StringBuilder
Your original loop works, but repeatedly concatenating strings with c += a can be inefficient for large values of b (each concatenation creates a new string object). For better performance, use haxe.StringBuilder to build the string in a mutable buffer:
class Test { static function main() { var a = "Text"; var b = 4; var sb = new haxe.StringBuilder(); for (i in 0...b) { sb.add(a); } trace(sb.toString()); // Output: TextTextTextText } }
3. Basic Loop (For Reference)
Just to confirm, your initial loop implementation is technically correct — it’s just not the most performant for large repetitions:
class Test { static function main() { var a = "Text"; var b = 4; var c = ""; for (i in 0...b) { c = c + a; } trace(c); // Output: TextTextTextText } }
In most cases, sticking with the built-in repeat method is the best choice — it’s concise, readable, and optimized under the hood.
内容的提问来源于stack exchange,提问作者0x.dummyVar

