Thursday, October 20, 2005

Find Out How Many Occurrences Of A Substring Are In A String

If you want to know how many occurrences of a substring you have in a string play around with the code below. The trick here is to take the total length of the string, subtract the same string minus the occurrences and divide by the length of the substring

For example
String is ’ABABABABZZZZZ’, length is 13
Substring is ’AB’ length is 2
Length of string minus all occurrences of substring is 5
So (13 -5) /2 =4 occurrences

DECLARE @chvString VARCHAR(500)
SELECT @chvString ='ababababajdfgrhgjrhgierghierabababaaaaaaaabbbbbbbaaaa'
DECLARE @chvSearchString VARCHAR(50)
SELECT @chvSearchString = 'ab'
SELECT LEN(@chvString) AS StringLength,
LEN(@chvSearchString) AS SearchForStringLength,(LEN(@chvString)-
(LEN(REPLACE(@chvString,@chvSearchString,''))))/LEN(@chvSearchString) AS HowManyOccurances

No comments: