Inspect Tallying and Replacing Example


Scenario - Tallying multiple strings and replacing the specific characters.

Code -

----+----1----+----2----+----3----+----4----+----5----+
       IDENTIFICATION DIVISION. 
       PROGRAM-ID. INSPCTTR.
       AUTHOR. MTH.

       DATA DIVISION.
       WORKING-STORAGE SECTION.

       01 WS-VAR.
          05 WS-DATA    PIC X(40) VALUE
             "COBOL LANGUAGE IS A HIGH LEVEL LANGUAGE".
          05 WS-CNT1    PIC 9(02).
          05 WS-CNT2    PIC 9(02).
          05 WS-CNT3    PIC 9(02).
 
       PROCEDURE DIVISION.

           DISPLAY "BEFORE REPLACING:  " WS-DATA.
           INSPECT   WS-DATA
            TALLYING WS-CNT1 FOR ALL SPACES BEFORE "HIGH"
                     WS-CNT2 FOR ALL "A" AFTER "IS"
                     WS-CNT3 FOR LEADING "C"
           REPLACING ALL SPACES BY "#" AFTER "LEVEL"
                     "LANGUAGE" BY "&&&&&&&&" BEFORE "HIGH"
                     "IS" BY "**".

           DISPLAY "WS-CNT1:     " WS-CNT1.
           DISPLAY "WS-CNT2:     " WS-CNT2.
           DISPLAY "WS-CNT3:     " WS-CNT3.
           DISPLAY "AFTER REPLACING:   " WS-DATA.

           STOP RUN.

Output -

BEFORE REPLACING:  COBOL LANGUAGE IS A HIGH LEVEL LANGUAGE 
WS-CNT1:     04
WS-CNT2:     03
WS-CNT3:     01
AFTER REPLACING:   COBOL &&&&&&&& ** A HIGH LEVEL#LANGUAGE#

Explaining Example -

In the above counting case,

  • SPACES before "HIGH" has 4 occurrences.
  • "A" has 3 occurrences before "IS".
  • "C" has only one occurrence of leading.

After counting, the results are WS-CNT1 = 04, WS-CNT2 = 03 and WS-CNT3 = 01.

In the above replacing case,

  • SPACES AFTER "LEVEL" replaced by "#".
  • "LANGUAGE" before "HIGH" replaced by "&&&&&&&&".
  • "IS" replaced by "**".

After replacements, the result is "COBOL &&&&&&&& ** A HIGH LEVEL#LANGUAGE###########".