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


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

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

     

    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

    举例演示:

  • 相关阅读:
    A Bug's Life(削弱版食物链)
    The Suspects
    Find The Multiple
    Lake Counting(dfs)
    经典dfs(depth-first search)
    喝啤酒(预防老年痴呆的深度搜索)
    C语言的位运算的优势 !
    Oil Deposits
    Catch That Cow
    HTML 003 元素
  • 原文地址:https://www.cnblogs.com/insus/p/10859306.html
Copyright © 2020-2023  润新知