Skip to content
STRING and INSPECT
step 1/5

Reading — step 1 of 5

Learn

~1 min readProcedures and Logic

COBOL has built-in verbs for string manipulation:

STRING — concatenate:

       01 GREETING  PIC X(50).
           STRING "Hello, " DELIMITED BY SIZE
                  NAME       DELIMITED BY "  "  *> stop at 2 spaces
                  "!"        DELIMITED BY SIZE
              INTO GREETING.

DELIMITED BY SIZE includes everything; DELIMITED BY value stops at the value.

UNSTRING — split:

       01 LINE     PIC X(80).
       01 PARTS.
           05 P1   PIC X(20).
           05 P2   PIC X(20).
       UNSTRING LINE DELIMITED BY ","
           INTO P1, P2.

INSPECT — count or replace within a string:

       01 TEXT      PIC X(20).
       01 N         PIC 9(2) VALUE 0.
           MOVE "hello world" TO TEXT.
           INSPECT TEXT TALLYING N FOR ALL "l".
           DISPLAY N.        *> 3

           INSPECT TEXT REPLACING ALL "l" BY "L".
           DISPLAY TEXT.     *> heLLo worLd

INSPECT patterns:

  • TALLYING var FOR ALL X — count occurrences
  • TALLYING var FOR LEADING X — count from start until non-X
  • REPLACING ALL X BY Y — replace every X with Y
  • CONVERTING X TO Y — character translation (X and Y same length)

Numeric formatting with MOVE:

       01 PRICE      PIC 9(5)V99 VALUE 1234.56.
       01 DISPLAY-PRICE  PIC $$$,$$9.99.   *> edit picture
           MOVE PRICE TO DISPLAY-PRICE.
           DISPLAY DISPLAY-PRICE.   *> $1,234.56

Edit pictures (Z, *, $, ,, ., +, -, CR, DB) format numbers for display — the original COBOL reporting feature.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…