How can I get the number of spaces in a string?
This seemingly simple problem does not have the most simple answer. I wish there was some sort of ValueCount() method in ColdFusion, but right, I think that only applies to List (ie. ListValueCount()). Luckily for your particular problem, there is a mostly simple solution. Since you are looking for just spaces, we can strip out everything that is NOT a space and then just get the length of the resultant string:
<cfset intLength = Len( REReplace( "You are simply a vision in that dress!", "[^ ]+", "", "ALL" ) ) />
This really only works when you are looking for single characters. If you want to search for all instances of a word, then things get a bit hairy. The easy solution is simple to keep searching the string untill you cannot find any instances.
<!--- The test value. ---> <cfset strTest = "You are the best and the most beautiful person." /> <!--- The target instance. ---> <cfset strTarget = "the" /> <!--- The instance counter. ---> <cfset intCount = 0 /> <!--- Get the initial position. ---> <cfset intPosition = Find( strTarget, strTest, 0 ) /> <!--- Keep searching till no more instances are found. ---> <cfloop condition="intPosition"> <!--- Increment instance counter. ---> <cfset intCount = (intCount + 1)> <!--- Get the next position. ---> <cfset intPosition = Find( strTarget, strTest, (intPosition + Len( strTarget )) ) /> </cfloop> <!--- Output the number of target instances. ---> #intCount#
Each time we do a search, we have to increment the counter and then start the search again after the given instance. Not the greatest solution, but it works.
Want to use code from this post? Check out the license.