How to count number of words in a sentence?

There was a question on counting number of words in a sentence by my friend

One simple method is use while loop as shown below

Declare @s varchar(100)
set @s='  See      how many                        words this      has  '
set @s=ltrim(rtrim(@s))

while charindex('  ',@s)>0
Begin
	set @s=replace(@s,'  ',' ')
end

select len(@s)-len(replace(@s,' ',''))+1 as word_count

The result is 6

If the sentence has multiple consecutive spaces, replace them with single space until no more multiple spaces exist. If you count number of spaces and add 1, it gives you the count of words

Advertisement