计算字符串由几个单词组成
字符串由几个单词组成,一般情况之下以空格分隔来计算即可。
实现方法,参考下面自定义函数:
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
举例演示: