Home Forums Programming General Reverse string without built in functions RE: Reverse string without built in functions

  • pshvets (4/14/2009)


    Hello all.

    I am trying to write a function which reverses passed string WITHOUT using any built-in functions

    So if 'abc' is passed, it returns 'cba'

    I want to use recursion. Here is what I got:

    create function StringReverse

    (

    @InString varchar(20)

    )

    returns varchar(20)

    AS

    begin

    declare @RevString varchar(20)

    IF len(@InString) in (0,1)

    set @RevString = @InString

    ELSE

    set @RevString =

    (

    dbo.StringReverse(substring(@InString, len(@InString)/2+1, len(@InString))

    +

    dbo.StringReverse(substring(@InString, 1, len(@InString)/2)))

    )

    return @RevString

    end

    It compiles fine, but when I call it, it throws an exception:

    select dbo.StringReverse('abc')

    Msg 217, Level 16, State 1, Line 1

    Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

    Why? Function calls itself at most 5 times:

    Pass1 - RevString('c') + RevString('ab')

    Pass2 - 'c' + (RevString(RevString('b') + RevString('a'))

    Pass3 - 'cba'

    Should I use a loop?

    Thanks in advance for your help!

    Pit

    The requirement of “Reverse string without built in functions” doesn’t make any sense, especially since all of the solutions posted, including yours, use built in functions.

    If it’s OK to use the built in DATALENGTH, SUBSTRING, RIGHT, LEFT, or LEN functions, why can’t you just use the built in REVERSE function?