17 December 2007 17:15 tonyrogerson

Counting the number of words in a string

Are you trying to count how many words there are in a string? Well, first I looked at the LEN and REPLACE ( ... ', ' ', '' ) method but you soon realise it doesn't work - you start counting double spaces as actual words.

Here is a function that gets round the problem; it also excludes non word stuff like a question mark.

create function fn_how_many_words(
    @source varchar(max) )

    returns int

as

begin

    declare @start int

 

    --  break any multiple spaces down

    while 1=1

    begin

        set @start = len( replace( @source, '  ', ' ' ) )

        set @source = replace( @source, '  ', ' ' )

 

        if @start = len( replace( @source, '  ', ' ' ) )

            break

 

    end

 

    --  get rid of any non letters and numbers

    set @start = 1

    while @start <= 255

    begin

        if @start not between ascii( 'a' ) and ascii( 'z' )

           and @start not between ascii( 'A' ) and ascii( 'Z' )

           and @start not between ascii( '0' ) and ascii( '9' )

           and @start <> ascii( ' ' )

 

            set @source = replace( @source, char( @start ), '' )

 

        set @start = @start + 1

 

    end

   

    return( len( @source ) - len( replace( @source, ' ', '' ) ) + 1 )

 

end

 

Filed under:

Comments

# re: Counting the number of words in a string

18 December 2007 08:32 by Madhivanan

Hi Tony,

You dont need while loop to remove multiple spaces

You can use this appraoch http://sqlblogcasts.com/blogs/madhivanan/archive/2007/12/06/squeeze-function.aspx

Declare @v1 varchar(8000)

set @v1='this                   is test   string    '

Declare @v2 varchar(8000)

select @v2= replace(replace(replace(@v1,' ',' ~!#$^'),'~!#$^ ',''),'~!#$^','')

select len(@v2)-len(replace(@v2,' ',''))+1

select dbo.fn_how_many_words(@v1)

# re: Counting the number of words in a string

18 December 2007 08:55 by tonyrogerson

Nice one Madhivanan.

I remember seeing your blog post now.

I like it - clever.

Tony.

# Interesting Finds: December 18, 2007

18 December 2007 17:08 by Jason Haley

# Count number of words in a string

21 December 2007 09:52 by Madhivanan

Tony Rogerson in his weblog posted on Counting the number of words in a string Here are two more methods

# Count number of words in a String

21 December 2007 10:10 by SQL Server Transact-SQL (SSQA.net)

Tony Rogerson in his weblog posted about Counting the number of words in a string Here are two more methods