CFLib.org – Common Function Library Project

getOccurrenceCount(content, countThis[, countThisDelimiter])

Last updated October 13, 2006

author

Cody Ridgway

Version: 1 | Requires: CF5 | Library: StrLib

Description:
Count the occurences of a value or list of values in a string. Pass the string (lists will be treated as strings) to parse and anything from a single character to a list of various items to count and the count or list of counts will be returned. Spaces in the item or list of items are not stripped.

Return Values:
Returns a string.

Example:

<cfset testString = "<b>This is a test string</b> with <i>text</i>, tags, || (pipes), and a 	 (tab) in it.">

<cfoutput>
#getOccurrenceCount(testString,"a")#<br>
#getOccurrenceCount(testString,"., ,<b>,<,text,#Chr(9)#")#<br>
#getOccurrenceCount(testString,",|text|#Chr(9)#", "|")#<br>
</cfoutput>

Parameters:

Name Description Required
content String to parse. Yes
countThis Character, or list of characters to count. Yes
countThisDelimiter Delimiter. Defaults to a comma. No

Full UDF Source:

/**
 * Count the occureneces of a value or list of values in a given string.
 * 
 * @param content 	 String to parse. (Required)
 * @param countThis 	 Character, or list of characters to count. (Required)
 * @param countThisDelimiter 	 Delimiter. Defaults to a comma. (Optional)
 * @return Returns a string. 
 * @author Cody Ridgway (cridgway@dcccd.edu) 
 * @version 1, October 13, 2006 
 */
function getOccurrenceCount(content, countThis) {
	var countThisDelimiter = ','; 
	var countThisLen = 1; 
	var countThisItem = ';
	var returnCount = ';
	var i = 1;
	
	if(arrayLen(Arguments) GT 2) countThisDelimiter = Left(arguments[3],1);
	countThisLen = ListLen(countThis, countThisDelimiter);
	
	if(countThisLen GT 1) {
		for(i=1; i LTE countThisLen; i=i+1){
			countThisItem = listGetAt(countThis, i, countThisDelimiter);
			returnCount = ListAppend(returnCount, val(len(content) - len(replace(content,countThisItem,"","all")))/Len(countThisItem));
		}
	}
	else{
		returnCount = val(len(content) - len(replace(content,countThis,"","all")))/Len(countThis);
	}
	return returnCount;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson