Technical Article

Counting ocurrences in a string

,

Counting the number of ocurrences of characters in a string can be useful, and this script will do the job. It can easily be modified to be a function or to search for ocurrences of strings. Run it in Query Analyzer.

DECLARE @s VARCHAR(50)  
DECLARE @c INT
DECLARE @a CHAR(1)

/*
The string to be searched.
*/SET @s = '1101001001110101'

/*
The character to be counted.
*/SET @a = '0'

/*
Replace the character to be counted with empty string, 
and subtract the lengths.
*/SET @c = LEN(@s) - LEN(REPLACE(@s,@a,''))

/*
Do something with the result
*/PRINT @c

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating