Skip to main content

Problem:

Often there is a need to be able to calculate the length of data within a COBOL string (PIC X).

Resolution:

There are many ways to calculate the length of data within a COBOL string variable.  The following method is simple and hopefully easy to understand.  The code basically does the following:

1) It reverses the string using the REVERSE Intrinsic function.

2) The INSPECT verb is used to count the number of leading spaces.

3) The number of leading spaces is subtracted from the total size of the variable.

Here is a small example that illustrates the idea:

       working-storage section.

       01  ws-string                   pic x(40).

       01  ws-string-len               pic 9(4).

       procedure division.

           display

              spaces at 0101

           end-display.

      * -- Empty string.

           move spaces to ws-string.

           perform proc-calc-len.

           display

              ws-string at 0101

              ws-string-len at 0201

           end-display.

      * -- Part filled string.

           move "Micro Focus" to ws-string.

           perform proc-calc-len.

           display

              ws-string at 0401

              ws-string-len at 0501

           end-display.

      * -- Completely filled string.

           move all "X" to ws-string.

           perform proc-calc-len.

           display

              ws-string at 0701

              ws-string-len at 0801

           end-display.

           stop run.

      * -------------------------------------------------------------- *

       proc-calc-len section.

           move 0 to ws-string-len.

           move function reverse(ws-string) to ws-string.

           inspect ws-string

              tallying ws-string-len

              for leading space.

           subtract ws-string-len

              from length of ws-string

              giving ws-string-len.

           move function reverse(ws-string) to ws-string.

       proc-calc-len-exit.

           exit.

      * -------------------------------------------------------------- *

Old KB# 4384