Reverse string in COBOL without using REVERSE function?

OS/VS COBOL, COBOL II, Enterprise COBOL for z/OS. OpenCOBOL and OOCobol.
Post Reply
alpna
Registered Member
Posts: 56
Joined: Fri Jun 21, 2013 10:35 pm

Reverse string in COBOL without using REVERSE function?

Post by alpna »

Can we reverse a string in COBOL without using REVERSE function? I ask this because we have an old training mainframe computer with old COBOL compiler and that does not support REVERSE function.
William Collins
Global Moderator
Global Moderator
Posts: 490
Joined: Sun Aug 25, 2013 7:24 pm

Re: Reverse string in COBOL without using REVERSE function?

Post by William Collins »

Of course you can. You'll need to define an intermediate byte, and have a loop. Save the next byte to the intermediate, MOVE the "opposite" byte (same count from the end of the data as next byte is from the beginning) to the next byte, and the saved byte to the opposite byte. Cycle the loop. Continue until the subscripts "meet" or "cross".
User avatar
Robert Sample
Global Moderator
Global Moderator
Posts: 1885
Joined: Fri Jun 28, 2013 1:22 am
Location: Dubuque Iowa
United States of America

Re: Reverse string in COBOL without using REVERSE function?

Post by Robert Sample »

If the compiler supports reference modification, use it. If not, you'll need to use REDEFINES to have your input and output variables accessible as an array of bytes.
alpna
Registered Member
Posts: 56
Joined: Fri Jun 21, 2013 10:35 pm

Re: Reverse string in COBOL without using REVERSE function?

Post by alpna »

For a continuous string of length 50, I have used the following logic, this seem to work:

Code: Select all

ws-counter=1 
Perform reverse-string-para 
varying ws-counter=1 from 50 by -1 
until ws-counter=0 

Reversa-para 
Move name(ws-counter:1) to namer(ws-counter2:1) 
ws-counter2=ws-counter2+1
William Collins
Global Moderator
Global Moderator
Posts: 490
Joined: Sun Aug 25, 2013 7:24 pm

Re: Reverse string in COBOL without using REVERSE function?

Post by William Collins »

Well, no, it doesn't work. Use a length of 10. Sit down with a pencil and paper and work out what happens with all spaces, one character plus nine spaces, five characters (plus space), nine (plus one space) and ten characters (plus no space).
Post Reply

Create an account or sign in to join the discussion

You need to be a member in order to post a reply

Create an account

Not a member? register to join our community
Members can start their own topics & subscribe to topics
It’s free and only takes a minute

Register

Sign in

Return to “IBM COBOL, GnuCOBOL (OpenCOBOL), OOCobol.”