Friday 26 August 2011

Reversing a String

Question:
I need a function that will return the reverse of a string. In other words, if I pass in "hello", I want to receive back "olleh." Does PL/SQL have a built-in function to do this for me?
Answer:
PL/SQL does not have a "reverse string" function, but it certainly is easy enough to build. Here is one possible implementation:
CREATE OR REPLACE FUNCTION revstr (
string_in IN VARCHAR2
)
RETURN VARCHAR2
IS
l_position PLS_INTEGER := 1;
l_length PLS_INTEGER := NVL (LENGTH (string_in), 0);
l_return VARCHAR2 (32767);
BEGIN
WHILE (l_position <= l_length)
LOOP
l_return := SUBSTR (string_in, l_position, 1) || l_return;
l_position := l_position + 1;
END LOOP;

RETURN l_return;
END revstr;
/

Note that I rely on the SUBSTR function, because I am determining position and length by character. If you are working with character sets that require specification of position and length by other means, you will need to switch to one of these variations of the SUBSTR function:
SUBSTRB – determine position and length by byte
SUBSTRC - determine position and length in Unicode characters
SUBSTR2 – use code units
SUBSTR4 – use code points

No comments:

Post a Comment