How to replace spaces at the right into zeros at the left in COBOL?

cobol, optimization

Solution

You should test your code with an input of all blanks.

If you are absolutely certain of the quality of the data, and with or without the check for blanks, you can do this:

   ID DIVISION.
   PROGRAM-ID. VARSWAP.
   DATA DIVISION.
   WORKING-STORAGE SECTION. 

       01 VARIN   PIC X(10).
          88  NO-VARIN-PRESENT VALUE SPACE.
       01 VARSWAP PIC 9(10).

   PROCEDURE DIVISION.

       MOVE '123456    ' TO VARIN
       IF NO-VARIN-PRESENT
           do what your spec says
       ELSE
           UNSTRING VARIN DELIMITED BY ' ' INTO VARSWAP
       END-IF

       DISPLAY VARSWAP

      GOBACK
      .

I don't like destroying the input, so I changed that.

A popular way to do it is, FUNCTION REVERSE ( your-field ), followed by INSPECT reversed-field TALLYING ... FOR LEADING SPACES. You can use FUNCTION LENGTH early in your program to determine the length of the fields (and ensure they are the same length) and then, setting your VARIN to ZERO first, use reference-modification for the source and the target - source will be ( 1 : calculated-length-of-data ) target will be ( calculated-start-for-right-justification : ) (not specifying the length uses the remaining part of the field).

There are also variable-length fields, byte-by-byte MOVEs (sometimes preferred by "traditionalists", but the least clear of the lot).

Exactly how you do it depends on your data. If you need to validate the data, you need code for that first, and that will make the choice more clear to you. If your data is, guaranteed, clean, then...

I know it is only an example, but I hope you use nicer data-names for real.

Problem

I have an alphanumeric variable with a length of 10. It contains a number at the beginning, the rest of the digits are filled with spaces. Then I need to move the string to the left and put the number of spaces with '0' at the begining. This examples speaks for themselves: ``` INPUT OUTPUT ============================== '123456 ' -> '0000123456' '12345678 ' -> '0012345678' '123456789 ' -> '0123456789' '1234567890' -> '1234567890' ``` Then I tought in something like this: Check this COBOL fiddle where you can try: http://ideone.com/mgbKZ3 (just click on edit) ``` IDENTIFICATION DIVISION. PROGRAM-ID. VARSWAP. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIN PIC X(10). 01 VARSWAP PIC X(10) JUSTIFIED RIGHT. PROCEDURE DIVISION. MOVE '123456 ' TO VARIN UNSTRING VARIN DELIMITED BY ' ' INTO VARSWAP INSPECT VARSWAP REPLACING LEADING SPACE BY '0' MOVE VARSWAP TO VARIN DISPLAY VARIN STOP RUN. ``` Returns: ``` 0000123456 ``` It seems work ok, but I wonder if you have a better, simpler, or clearer way to do it.

Original source