Monday 7 May 2012

Count number of occurance of a character in a string

Using string length
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform&quot;
xmlns:xs="http://www.w3.org/2001/XMLSchema&quot; exclude-result-prefixes="xs" version="2.0">
<xsl:param name="string" select="'vishnu singh'"></xsl:param>
<xsl:template match="/">
<xsl:value-of select="string-length($string)-string-length(translate($string,'h',''))"></xsl:value-of>
</xsl:template>
</xsl:stylesheet>




Using Recursion

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform&quot;
xmlns:xs="http://www.w3.org/2001/XMLSchema&quot; exclude-result-prefixes="xs" version="2.0"
xmlns:inno="www.w3c.org.com">
<xsl:param name="text">navin rawat</xsl:param>
<xsl:template match="/">
<xsl:call-template name="count">
<xsl:with-param name="text" select="$text"/>
<xsl:with-param name="character" select="'a'"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="count">
<xsl:param name="text" as="xs:string"/>
<xsl:param name="character" as="xs:string"/>
<xsl:param name="count" select="0" as="xs:integer"/>
<xsl:choose>
<xsl:when test="contains($text,$character)">
<xsl:call-template name="count">
<xsl:with-param name="character" select="$character"/>
<xsl:with-param name="text" select="substring-after($text,$character)"/>
<xsl:with-param name="count" select="sum($count + 1)"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$count"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Another method to count a character within a string
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform&quot;
xmlns:xs="http://www.w3.org/2001/XMLSchema&quot; exclude-result-prefixes="xs" version="2.0">
<xsl:param name="string" select="'vishnu singh'"></xsl:param>
<xsl:template match="/">
<xsl:value-of select="count(tokenize($string,'s'))-1"></xsl:value-of>
</xsl:template>
</xsl:stylesheet>



1 comment:

Anonymous said...

Good one :)

~~ Abhinav