Reverse a string in PL/SQL

Prerequisite PL/SQL introduction

In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.

Given a string, the task is to reverse a string using PL/SQL.



Examples:

Input: skeegrofskeeg
Output: geeksforgeeks

Input: geeks
Output: skeeg

Approach:

  • Find the length of the string.
  • Then traverse the string in a reverse manner.
  • Store the characters in another string.
  • Print the final string.

Below is the required implementation:

filter_none

edit
close

play_arrow

link
brightness_4
code

DECLARE
    -- declare variable str , len 
    -- and str1 of datatype varchar
    str  VARCHAR(20) := 'skeegrofskeeg';
    len  NUMBER;
    str1 VARCHAR(20);
BEGIN
    -- Here we find the length of string
    len := Length(str);
  
    -- here we starting a loop from max len to 1
    FOR i IN REVERSE 1.. len LOOP
        -- assigning the reverse string in str1               
        str1 := str1
                || Substr(str, i, 1);
    END LOOP;
  
    dbms_output.Put_line('Reverse of string is '
                         || str1);
END;
-- Program End 

chevron_right


Output :

Reverse of string is geeksforgeeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.