[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

Re: [xsl] Counting occurences of a character in a string


Subject: Re: [xsl] Counting occurences of a character in a string
From: "Dimitre Novatchev" <dnovatchev@xxxxxxxxx>
Date: Tue, 1 Apr 2008 22:32:19 -0700

Here are three different ways. The first is the shortest and probably
the fastest. The second uses Dr. Kay's "double-translate" method.

The third illustrates how in FXSL one can glue-up functions to produce
quick solutions.

Please, do note, that the character to search for is contained in a
variable -- it seems to me that the solutions offered so far all used
the fixed character "X". They would have to build an RegEx expression
dynamically if this character was not known at compile time.

This transformation:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:f="http://fxsl.sf.net/"
 exclude-result-prefixes="f xs"
 >

 <xsl:import href="C:/CVS-DDN/fxsl-xslt2/f/func-map.xsl"/>
 <xsl:import href="C:/CVS-DDN/fxsl-xslt2/f/func-compose.xsl"/>
 <xsl:import href="C:/CVS-DDN/fxsl-xslt2/f/func-dvc-foldl.xsl"/>
 <xsl:import href="C:/CVS-DDN/fxsl-xslt2/f/func-Operators.xsl"/>
 <xsl:import href="C:/CVS-DDN/fxsl-xslt2/f/func-standardXpathFunctions.xsl"/>

 <xsl:output method="text"/>

  <xsl:variable name="vS" as="xs:string"
    select="'abbccddd e fgggggi ggg kk l'"/>

  <xsl:variable name="vX" as="xs:string"
   select="'g'"/>

  <xsl:variable name="vcpX" as="xs:integer"
   select="string-to-codepoints('g')"/>

 <xsl:template match="/">
  <xsl:sequence select=
   "count(string-to-codepoints($vS)[. eq $vcpX])"
  />

  <xsl:sequence select=
      "string-length(translate($vS,translate($vS,$vX,''),''))"
  />

  <xsl:sequence select=
      "f:foldl(f:add(),
               0,
               f:map(f:compose(f:number(), f:eq($vcpX)),
                     string-to-codepoints($vS)
                     )
               )"
  />


 </xsl:template>
</xsl:stylesheet>

produces this result:


8 8 8



-- 
Cheers,
Dimitre Novatchev
---------------------------------------
Truly great madness cannot be achieved without significant intelligence.
---------------------------------------
To invent, you need a good imagination and a pile of junk
-------------------------------------
Never fight an inanimate object
-------------------------------------
You've achieved success in your field when you don't know whether what
you're doing is work or play





On Tue, Apr 1, 2008 at 3:01 PM, Christian Roth <roth@xxxxxxxxxxxxxx> wrote:
> Hello,
>
> in XSLT 2, is there an easier or more efficient way to count the
> occurrences of a certain character (here: 'X') in a string $s than
>
> string-length( string-join( tokenize( $s, "[^X]+" ), "" ) )
>
> ?
>
> I'm sure there must be, I just don't see it at the moment...
>
> -Christian


Current Thread
Keywords