There are several ways to count for the number of times a certain character occurs in a given string. Now we will see some of the ways.
First Method:
One of the ways to count for the number of times a certain character occurs in a given string is to loop through each character of the string and compare the character.
- CREATE FUNCTION [dbo].[ufn_CountChar] ( @InputStr VARCHAR(1000), @SearchChar CHAR(1) )
- RETURNS INT
- BEGIN
- DECLARE @StrLength INT
- DECLARE @index INT
- DECLARE @CharCount INT
-
- SET @CharCount = 0
- SET @index = 1
- SET @StrLength = LEN(@InputStr)
-
- WHILE @index <= @StrLength
- BEGIN
- IF SUBSTRING(@InputStr, @index, 1) = @SearchChar
- SET @CharCount = @CharCount + 1
- SET @index = @index + 1
- END
- RETURN @CharCount
- END
- GO
Second Method:
Another way of determining the number of times a certain character occur in a given string without the use of a loop.
- CREATE FUNCTION [dbo].[ufn_CountChar] ( @InputStr VARCHAR(1000), @SearchChar CHAR(1) )
- RETURNS INT
- BEGIN
- RETURN (LEN(@InputStr) - LEN(REPLACE(@InputStr, @SearchChar, '')))
- END
- GO