Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply strings in Haxe

Tags:

string

haxe

I'm trying to multiply some string a by some integer b such that a * b = a + a + a... (b times). I've tried doing it the same way I would in python:

class Test {
    static function main() {
        var a = "Text";
        var b = 4;    
        trace(a * b);    //Assumed Output: TextTextTextText
    }
}

But this raises:

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

There doesn't seem to be any information in the Haxe Programming Cookbook or the API Documentation about multiplying strings, so I'm wondering if I've mistyped something or if I should use:

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"
    }
}
like image 589
0x.dummyVar Avatar asked Dec 10 '22 08:12

0x.dummyVar


2 Answers

Not very short, but array comprehension might help in some situations :

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

See on try.haxe.org.

like image 172
tokiop Avatar answered Dec 23 '22 07:12

tokiop


The numeric multiplication operator * requires numeric types, like integer. You have a string. If you want to multiply a string, you have to do it manually by appending a target string within the loop.

The + operator is not the numeric plus in your example, but a way to combine strings.

You can achieve what you want by operator 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
    }
}
like image 25
k0pernikus Avatar answered Dec 23 '22 08:12

k0pernikus