如何在 Haxe 中乘以字符串

How to multiply strings in Haxe

我正在尝试将一些字符串 a 乘以一些整数 b 这样 a * b = a + a + a...(b 次)。我试过按照 python:

中的方式进行操作
class Test {
    static function main() {
        var a = "Text";
        var b = 4;    
        trace(a * b);    //Assumed Output: TextTextTextText
    }
}

但这引发了:

Build failure Test.hx:6: characters 14-15 : String should be Int

Haxe Programming Cookbook 或 API 文档中似乎没有任何关于乘法字符串的信息,所以我想知道我是否打错了什么或者我是否应该使用:

class Test {
    static function main() {
        var a = "Text";
        var b = 4;
        var c = ""; 

        for (i in 0...b) {
            c = c + a;
        }
        trace(c); // Outputs "TextTextTextText"
    }
}

数字乘法运算符 * 需要数字类型,例如整数。你有一个字符串。如果你想乘以一个字符串,你必须通过在循环中附加一个目标字符串来手动完成。

+ 运算符不是您示例中的数字加号,而是一种组合字符串的方法。

你可以通过运算符overloading:

实现你想要的
abstract MyAbstract(String) {
    public inline function new(s:String) {
        this = s;
    }

    @:op(A * B)
    public function repeat(rhs:Int):MyAbstract {
        var s:StringBuf = new StringBuf();
        for (i in 0...rhs)
            s.add(this);
        return new MyAbstract(s.toString());
    }
}

class Main {
    static public function main() {
        var a = new MyAbstract("foo");
        trace(a * 3); // foofoofoo
    }
}

不是很短,但 array comprehension 在某些情况下可能会有所帮助:

class Test {
    static function main() {
        var a = "Text";
        var b = 4;
        trace( [for (i in 0...b) a].join("") );
        //Output: TextTextTextText
    }
}

try.haxe.org

要在 上构建,您还可以定义一个 times 函数,然后将其用作静态扩展。

using Test.Extensions;

class Test {
    static function main() {
        trace ("Text".times(4));
    }
}

class Extensions {
    public static function times (str:String, n:Int) {
        return [for (i in 0...n) str].join("");
    }
}

try.haxe.org demo here

要建立在 bsinky 答案之上,您还可以将 times 函数定义为静态扩展,但要避免使用数组:

using Test.Extensions;

class Test {
    static function main() {
        trace ("Text".times(4));
    }
}

class Extensions {
    public static function times (str:String, n:Int) {
        var v = new StringBuf();
        for (i in 0...n) v.add(str);
        return v.toString();
    }
}

演示:https://try.haxe.org/#e5937

StringBuf may be optimized for different targets. For example, on JavaScript target it is compiled as if you were just using strings https://api.haxe.org/StringBuf.html

最快的方法(至少在 https://try.haxe.org/#195A8 的 JavaScript 目标上)似乎是使用 StringTools._pad

public static inline function stringProduct ( s : String, n : Int ) {

    if ( n < 0 ) {

        throw ( 1 );

    }

    return StringTools.lpad ( "", s, s.length * n );

}

StringTools.lpadStringTools.rpad 似乎无法决定哪个更有效率。看起来 rpad 可能更适合较大的字符串,而 lpad 可能更适合较小的字符串,但每次重新运行时它们都会稍微切换一下。 haxe.format.JsonPrinter 使用 lpad 进行连接,但我不确定推荐哪个。