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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s