You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haxe中如何实现字符串重复拼接(类似Python的字符串乘法)

How to Repeat a String Multiple Times in Haxe

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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:45:57