Link to home
Start Free TrialLog in
Avatar of Larry Brister
Larry BristerFlag for United States of America

asked on

Determine if a string is just a repeating character

I would like to have a function that I feed in a string
And if that string is simply the same repeating character
Example... (aaaaaaaaaaaaa) or (11111111111111)
Return 1
Else
Return 0
Avatar of Arana (G.P.)
Arana (G.P.)

is this still valid if string contains at least one other character at the end? or will that return CERO?


AAAAAAAAAAAAAAB = 0?
ASKER CERTIFIED SOLUTION
Avatar of Arana (G.P.)
Arana (G.P.)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Larry Brister

ASKER

Perfect
I created this function...

CREATE FUNCTION fnIsRepeatingString
(
    @mystring VARCHAR(1000)
)
RETURNS BIT
AS
BEGIN

    DECLARE @ResultVar BIT = 0;

    IF REPLICATE(LEFT(@mystring, 1), LEN(@mystring)) = @mystring
    BEGIN
        SET @ResultVar = 1;
    END;
    -- Return the result of the function
    RETURN @ResultVar;

END;

Open in new window

Adding any local variable to a function adds overhead (a memory allocation must be done).  Do this instead:

SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE FUNCTION fnIsRepeatingString
(
    @mystring VARCHAR(1000)
)
RETURNS BIT
AS
BEGIN
RETURN (
   
    SELECT CASE WHEN REPLICATE(LEFT(@mystring, 1), LEN(@mystring)) = @mystring
        THEN 1 ELSE 0 END

)
END;