asp.net計算一串數字中每個數字出現的次數

來源:互聯網
上載者:User

接下來拆分這一串字串,每個字元插入一個表變數中,最後使用GROUP BY進行分組。 複製代碼 代碼如下:CalNumOfChtInStr
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Insus.NET
-- Create date: 2012-02-23
-- Description: Calculate the number of characters in the string
-- =============================================
CREATE PROCEDURE [dbo].[CalNumOfChtInStr]
(
@Value NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @dum TABLE ([Str] NVARCHAR(2))
DECLARE @I INT = LEN(@Value),@J INT = LEN(@Value)
WHILE @I > 0
BEGIN
--以下函數可參考:http://www.cnblogs.com/insus/archive/2011/06/25/2090231.html
IF [dbo].[IsInteger] (SUBSTRING(@Value, @I, 1)) = 0
BEGIN
RAISERROR('傳入字串包含其它字元,不完全是數字。',16,1)
RETURN
END
SET @I = @I - 1
END
WHILE @J > 0
BEGIN
INSERT INTO @dum VALUES(SUBSTRING(@Value, @J, 1))
SET @J = @J - 1
END
SELECT [Str],COUNT([Str]) AS [Num] FROM @dum GROUP BY [Str]
END

Demo: 複製代碼 代碼如下:EXECUTE [dbo].[CalNumOfChtInStr] '5487554127489423454'

結果:


以下文字更新於2012-02-24 09:40
分析以上的預存程序,考慮到效能問題,它在判斷是否包含有其它字元時,迴圈一次字串,然後又迴圈一次將每一個字元插入表變數中。以下修改正此點只做迴圈一次。

複製代碼 代碼如下:CalNumOfChtInStr
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Insus.NET
-- Create date: 2012-02-23
-- Update date: 2012-02-24
-- Description: Calculate the number of characters in the string
-- =============================================

ALTER PROCEDURE [dbo].[CalNumOfChtInStr]
(
@Value NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @dum TABLE ([Str] NVARCHAR(2))
DECLARE @I INT = LEN(@Value)
WHILE @I > 0
BEGIN
INSERT INTO @dum VALUES(SUBSTRING(@Value, @I, 1))
SET @I = @I - 1
END

--以下函數可參考:http://www.cnblogs.com/insus/archive/2011/06/25/2090231.html
IF EXISTS(SELECT TOP 1 1 FROM @dum WHERE [dbo].[IsInteger]([Str]) = 0)
BEGIN
RAISERROR('傳入字串包含其它字元,不完全是數字。',16,1)
RETURN
END
SELECT [Str],COUNT([Str]) AS [Num] FROM @dum GROUP BY [Str]
END

以下內容於2012-04-29 10:44分添加:

如果想參考C#版本 http://www.jb51.net/article/30211.htm

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.