1. 程式人生 > >計算字符串由幾個單詞組成

計算字符串由幾個單詞組成

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: 計算字符串由幾個單詞組成
-- =============================================
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
Source Code

舉例演示:

技術分享圖片

計算字符串由幾個單詞組成