Technical Article

Counting occurrences of a substring in a string

,

Modification of the script entitled "Counting occurrences in a string" by thomasun.

This version, packaged as a UDF, is not limited to searching for single characters - substrings can be counted.

CREATE FUNCTION dbo.fnOccurs
(
  @searchIn  varchar(8000),  -- The string to be searched.
  @searchFor varchar(8000)   -- The string to be counted.
)
RETURNS int
BEGIN
  DECLARE @len_diff int

  -- Returns number of times a string occurs in another string.

  -- The first length calculation is the original size minus the number of 
  -- occurrences of the search string times the length of the search string.
  -- So, we then simply divide that result by the length of the search string
  -- to get the number of occurrences.

  SET @len_diff = Len(@searchIn) - Len(Replace(@searchIn, @searchFor, ''))
  SET @len_diff = @len_diff / Len(@searchFor)

  RETURN @len_diff
END

GO
-- Test it
PRINT dbo.fnOccurs('This string contains 2 occurrences of the word string.', 'string')
PRINT dbo.fnOccurs('This string contains 1 occurrences of s-t-r-i-n-g without the dashes.', 'string')
PRINT dbo.fnOccurs('This s-t-r-i-n-g contains 1 occurrences of s-t-r-i-n-g without the dashes.', 'string')

Rate

5 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

5 (1)

You rated this post out of 5. Change rating