Hello Readers!
Have you ever wanted to REVERSE a string a Mainframe COBOL program, or have you ever been asked to reverse a string without using REVERSE function? If the answer is Yes, then you may find this post useful to you.
In the below mentioned COBOL program, I used two different ways of reversing a string in COBOL program.
- Using FUNCTION REVERSE
- REVERSE function returns a character string of exactly same length as input, but in the reverse order.
- Using PERFORM VARYING UNTIL
- In this logic, we loop through each character of input string from end of input (i.e. Length) to beginning of input (i.e. Position=1) and store the characters in result variable using reference modification.
Output:
From the output, we can say that we are able to reverse the input, but have you noticed something? Reverse string output has leading spaces. It is because string variable is declared with 20 length, but the actual length length of string (i.e. z/OS Mainframer ) is 15.As input WS-STRING is Alphanumeric type, the value will be LEFT justified and the unoccupied positions will have the spaces (i.e. "z/OS Mainframer "). Hence, we are seeing the 5 leading spaces in the reversed string.
If we are asked not to use any functions in reversing the input data, We can eliminate the leading or trailing spaces from the input and usage of REVERSE function using PERFORM VARYING UNTIL loop and determine the actual start & end of the input data. This way we will be able to eliminate the unnecessary spaces and extract only required data from input.
Output:
If we are allowed to use any functions of COBOL for reversing the input value, then it is just one line code using TRIM & REVERSE functions as mentioned in the below code snippet.Output:
We can also use INSPECT TALLYING for knowing the LEADING SPACES count and PERFORM VARYING UNTIL for trailing spaces count. I hope this post is helpful in understanding the different ways of reversing the data in COBOL.
Please feel free to comment if there is any other way or suggestions.
Happy Learning & Sharing!!!
Happy Learning & Sharing!!!
Comments
Post a Comment