Thursday, February 28, 2013

Reversing a String in COBOL

The INSPECT VERB or the REVERSE FUNCTION might easily solve this question.
But coming up with a logic for the same is a puzzle.

Lets say we are given 2 string data-items as follows and we want 'AIDNI' to get populated into the second dada-item:

77 WS-STRING1 PIC X(5) VALUE 'INDIA'.
77 WS-STRING2 PIC X(5).

Declare another data-item WS-COUNTER to 5.

77 WS-COUNTER PIC X(5).

Perform the following logic till WS-COUNTER is 1.

IF WS-COUNTER = SPACES
     SUBTRACT 1 FROM WS-COUNTER GIVING WS-COUNTER
ELSE
     MOVE WS-STRING1(WS-COUNTER:1) TO WS-STRING2
     SUBTRACT 1 FROM WS-COUNTER GIVING WS-COUNTER
END-IF.

DISPLAY WS-STRING1.
DISPLAY WS-STRING2.

And we get the desired O/P in teh spool as follows:
********************
INDIA
AIDNI
********************

Problem solved! :)





No comments:

Post a Comment