December 2002
Intermediate to advanced
672 pages
16h 53m
English
You need to duplicate a
string N times, where N is a
parameter. For example, you might need to pad out a string with
spaces to achieve alignment.
A nice solution is a recursive approach that doubles the input string
until it is the required length while being careful to handle cases
in which $count is odd:
<xsl:template name="dup">
<xsl:param name="input"/>
<xsl:param name="count" select="1"/>
<xsl:choose>
<xsl:when test="not($count) or not($input)"/>
<xsl:when test="$count = 1">
<xsl:value-of select="$input"/>
</xsl:when>
<xsl:otherwise>
<!-- If $count is odd append an extra copy of input -->
<xsl:if test="$count mod 2">
<xsl:value-of select="$input"/>
</xsl:if>
<!-- Recursively apply template after doubling input and
halving count -->
<xsl:call-template name="dup">
<xsl:with-param name="input"
select="concat($input,$input)"/>
<xsl:with-param name="count"
select="floor($count div 2)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>The most obvious way to duplicate a string $count
times is to
figure out a way to concatenate the string to itself
$count-1 times. This can be done recursively by
the following code, but this code will be expensive unless
$count is small, so it is not recommended:
<xsl:template name="slow-dup"> <xsl:param name="input"/> <xsl:param name="count" select="1"/> <xsl:param name="work" select="$input"/> <xsl:choose> <xsl:when test="not($count) or not($input)"/> <xsl:when test="$count=1"> ...
Read now
Unlock full access