Skip to main content
July 1, 2008
Question

Count Substring in String

  • July 1, 2008
  • 6 replies
  • 1761 views
Is there any way you can count the number of substrings in a string using Coldfusion?

E.g.
haystack = 25fdjkkjlafjkl25alksdfjaafdjk25sl
needle = 25

result = 3
    This topic has been closed for replies.

    6 replies

    July 1, 2008
    No - I wanted to count the actual number of slashes - so for the URL of this post ( http://www.adobe.com/cfusion/webforums/forum/messageview.cfm) I wanted to have the number 6 returned.
    Inspiring
    July 1, 2008
    eightcharacters wrote:
    > True - In my case I was looking to count the number of slashes in a file/directory name from cfdirectory to determine how deep a file was in that directory.

    Do you want the number of slashes or the number of elements between the
    slashes?

    If the latter the more common code would be:

    <cfoutput>#listLen("Path/To/My/File.txt","/")#</cfoutput>
    July 1, 2008
    True - In my case I was looking to count the number of slashes in a file/directory name from cfdirectory to determine how deep a file was in that directory.
    July 1, 2008
    In most cases it is probably ok. You might possible want to use a case sensitve replace. You would see a difference in outputt between this method and if you wrote a loop to scan for the string. For example if haystack = '2525252' and needle = '252' the result would be 2 instead of 3 because the overlap is not considered.
    July 1, 2008
    That works perfectly - not quite sure how yet! (need to do some more looking at what it's actually doing - but it works perfectly.

    Thanks.
    July 1, 2008
    Try something like the following.
    Have not tested this yet.

    <cfset haystack = '25fdjkkjlafjkl25alksdfjaafdjk25sl'>
    <cfset needle = '25'>
    <cfset result = (len(haystack) - len(ReplaceNoCase(haystack,needle,'','ALL'))/len(needle)>