Count Occurences of Substring in a String

rudy? maybe im not following what it is you were trying to do there, but I don’t think that is what he is after.

Using this code:


<cfset variables.string = "the quick brown fox jumped over the red bridge" />
<cfset variables.substring = "the" />

<cfset occurrences = Len(Replace(variables.string,variables.substring,'','all')) / Len(variables.substring) >
    
<cfdump var="#occurrences#">

which should be counting the number of times the word “the” occurres, I get 13.3333, which I don’t think is correct. Or am I misusing your code?

I would use a function like this:


<cffunction name="countOccurrences" access="public" returntype="numeric" required="true">
    <cfargument name="string" type="string" required="True" />
    <cfargument name="subString" type="string" required="True" />
    
    <cfset VAR position = findNoCase(arguments.substring,arguments.string,1) />
    <cfset VAR count = 0 />
    
    <cfif len(trim(arguments.substring))>
        <cfloop condition="position NEQ 0">
            <cfset count = count + 1 />
            <cfset position = findNoCase(arguments.substring,arguments.string, position + len(trim(arguments.substring))) />
        </cfloop>
    <cfelse>
        <cfreturn 0 />
    </cfif>

<cfreturn count />
</cffunction>

then you can just call it whenever you need, pass it the full string, pass it the string you are looking for, and it returns a number of how many times it occurs.