計算字符串由幾個單詞組成
阿新 • • 發佈:2019-05-14
while input ansi substring arc ring 單詞 ins 參考
字符串由幾個單詞組成,一般情況之下以空格分隔來計算即可。
實現方法,參考下面自定義函數:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Insus.NET -- Create date: 2019-05-13 -- Update date: 2019-05-13 -- Description: 計算字符串由幾個單詞組成 -- =============================================Source CodeCREATE 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
舉例演示:
計算字符串由幾個單詞組成