欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

计算字符串由几个单词组成

程序员文章站 2022-09-30 21:19:14
字符串由几个单词组成,一般情况之下以空格分隔来计算即可。 实现方法,参考下面自定义函数: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- -- Author: Insus.NET -- Create date: 2019-05-13 -- Up ......

字符串由几个单词组成,一般情况之下以空格分隔来计算即可。

实现方法,参考下面自定义函数:

 

 

set ansi_nulls on
go
set quoted_identifier on
go
-- =============================================
-- author:      insus.net
-- create date: 2019-05-13
-- update date: 2019-05-13
-- description: 计算字符串由几个单词组成
-- =============================================
create function [dbo].[svf_wordcount] 
( 
    @inputstring nvarchar(max)
) 
returns int
as
begin
    declare @index int = 1
    declare @currentchar char(1)
    declare @previouschar char(1)
    declare @wordcount int = 0

    while @index <= len(@inputstring)
    begin
        set @currentchar = substring(@inputstring, @index, 1)
        set @previouschar = substring(@inputstring, @index - 1, 1)
            
        if @previouschar = ' ' and @currentchar != ' '                
            set @wordcount = @wordcount + 1

        set @index = @index + 1
    end
    return @wordcount
end
go

 

举例演示: