Jack Fleeting
Jack Fleeting

Reputation: 24928

Multiply a string by an integer?

In python, for example, I can do this

"X" * 3

or, more importantly (in this case)

"XO" * 3

and get XXX and XOXOXO, respectively.

I'm trying to replicate this with xpath/xquery. Ideally, it should be something like

"XO" * count(something)

The closest I could get is by sort of faking the output by creating a string with a length close to my estimate of what count(something) is going to be and then slice it with substring(). So if my count(something) returns 2

substring("XXX",1,count(//something))

would return XX. It gets slightly more complicated if my string is XO, in which case I have to modify it to

substring("XOXOXO",1,count(//something) * 2)

to get XOXO.

However, in addition to feeling hacky, these require an estimate of count() and the creation of a string of the correct length (+ some safety margin).

Is there a better way to do it in xpath or xquery?

Upvotes: 1

Views: 101

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

You can use ((1 to 3) ! 'XO') => string-join() and of course you can put that into a function if you like with a parameter for the string and the number of "multiplications" you want:

declare function local:multiply-string($input as xs:string, $factor as xs:integer) as xs:string
{
   ((1 to $factor) ! $input) => string-join() 
};

local:multiply-string('XO', 3)

https://xqueryfiddle.liberty-development.net/pPqteBa/1

Upvotes: 5

Related Questions