Friday, June 11, 2010

How To Count the Number of Occurrences of a word in a Sentence

A very simple method to find out the Number of Occurrences of a word in a sentence is by using the String Functions     Len() and Replace().

Let us take a tongue twister.

"I wish to wish the wish you wish to wish, but if you wish the wish the witch wishes, I won't wish the wish you wish to wish"

Now we want to find out the number of occurrences of the word "wish" in the above sentence.

This can be done by the following Code:

Declare @Str Varchar(500)

Set @Str = 'I wish to wish the wish you wish to wish, but if you wish the wish the witch wishes, I won''t wish the wish you wish to wish'

Select (LEN(@Str) - LEN(REPLACE(@Str, 'wish', ''))) / LEN('wish') [Word Count]

And The Out put is :

image

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.