Skip to content
LumenaryAcademy
Practice 60 min

Tables and strings

Arrays the COBOL way with OCCURS, linear and binary search, and taking text apart and putting it together with STRING, UNSTRING, INSPECT and reference modification.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Lists of things, and text from outside

Business programs constantly need two things that lesson 4's programs did not have. The first is a table: twelve monthly totals, the tax bands of a country, a list of currency rates, the lines of an invoice. The second is text handling: the world sends data as comma-separated lines, names with spaces in them, phone numbers in a dozen formats and card numbers that must be masked before they are printed.

COBOL handles both in its own way. A table is not an object you create at run time; it is a repeated field in the data division, declared with OCCURS, of a size fixed when you compile. Strings are fixed-width fields too, so instead of string objects that grow and shrink, COBOL gives you statements that copy text into fixed fields piece by piece: STRING, UNSTRING, INSPECT, and the ability to address any slice of a field directly. Once you are used to it, it is a precise and efficient model. It is also where many subtle bugs live, so this lesson pays attention to the traps.

DefinitionsH

OCCURS, subscripts and indexes

Definition— Table

A data item declared with OCCURS n TIMES, which the compiler lays out as n consecutive copies. Each copy is an element, reached with a subscript in brackets: rain-mm(3) is the third element. Subscripts start at 1, not 0.

cobol
01 sales-by-region.
   05 region OCCURS 4 TIMES.
      10 region-name      PIC X(10).
      10 quarter-sales    PIC S9(7)V99 COMP-3 OCCURS 4 TIMES.

This two-level table has four regions, each with a name and four quarterly figures: quarter-sales(2, 3) is the third quarter of the second region. COBOL allows at least seven levels of nesting.

A table element can be addressed in two ways:

  • With a subscript: an integer literal or a numeric data item, ideally COMP. The compiler multiplies by the element size at run time.
  • With an index, declared by INDEXED BY ri on the OCCURS clause. An index is not an ordinary number: it holds a ready-computed position, and you change it only with SET ri TO 1, SET ri UP BY 1 or as a loop variable in PERFORM VARYING. Indexes are required by SEARCH and are usually faster.

OCCURS ... DEPENDING ON count declares a table whose current length is held in another field, up to a fixed maximum. It is common in records that contain a variable number of items, such as an order with between one and fifty lines.

Since COBOL tables are fixed in the data division, how do you put constant data into one? The classic idiom declares the data as FILLER items with VALUE clauses, then redefines the same bytes as a table. You will see it in both programs below.

Worked examplesH

Tables at work

Totals, maximum and a bar chart

This program holds a year of monthly rainfall for a city (invented figures) and prints a small text chart:

cobol
IDENTIFICATION DIVISION.
PROGRAM-ID. rainfall.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 month-name-values.
   05 FILLER PIC X(36) VALUE "JanFebMarAprMayJunJulAugSepOctNovDec".
01 month-names REDEFINES month-name-values.
   05 month-name        PIC X(3) OCCURS 12 TIMES.
01 rainfall-values.
   05 FILLER PIC X(48) VALUE
      "008200670102015802110134008700590143020301760121".
01 rainfall-table REDEFINES rainfall-values.
   05 rain-mm           PIC 9(4) OCCURS 12 TIMES.
01 m                    PIC 99.
01 wettest              PIC 99 VALUE 1.
01 total-mm             PIC 9(5) VALUE 0.
01 average-mm           PIC 9(4)V9.
01 rain-bar             PIC X(30) VALUE ALL "#".
01 bar-length           PIC 99.
01 mm-out               PIC ZZZ9.
01 total-out            PIC ZZ,ZZ9.
01 avg-out              PIC ZZZ9.9.
PROCEDURE DIVISION.
    PERFORM VARYING m FROM 1 BY 1 UNTIL m > 12
        ADD rain-mm(m) TO total-mm
        IF rain-mm(m) > rain-mm(wettest)
            MOVE m TO wettest
        END-IF
        COMPUTE bar-length = rain-mm(m) / 10
        MOVE rain-mm(m) TO mm-out
        DISPLAY month-name(m) " " mm-out " " rain-bar(1:bar-length)
    END-PERFORM
    COMPUTE average-mm ROUNDED = total-mm / 12
    MOVE total-mm TO total-out
    MOVE average-mm TO avg-out
    DISPLAY "Total" total-out " mm, average" avg-out " mm, wettest "
            month-name(wettest)
    STOP RUN.
text
Jan   82 ########
Feb   67 ######
Mar  102 ##########
Apr  158 ###############
May  211 #####################
Jun  134 #############
Jul   87 ########
Aug   59 #####
Sep  143 ##############
Oct  203 ####################
Nov  176 #################
Dec  121 ############
Total 1,543 mm, average 128.6 mm, wettest May

The 48-character literal is twelve four-digit numbers side by side; the REDEFINES makes those same bytes a table of PIC 9(4) elements. The month names work the same way, three letters each. rain-bar(1:bar-length) is reference modification: the first bar-length characters of a 30-character field full of #. We return to it with strings below. And wettest holds a subscript rather than a value, so at the end it can name the month as well as find the amount.

SEARCH and SEARCH ALL

To find an entry by its key, COBOL offers two statements. SEARCH is a linear search: it starts at the current index value and tests elements one by one. SEARCH ALL is a binary search: it halves the range at each step, so it needs about log⁡2n\log_2 n comparisons instead of up to nn, but it requires that the table is declared with ASCENDING KEY (or DESCENDING KEY) and that the data really is in that order.

The rates below are illustrative, not real exchange rates:

cobol
IDENTIFICATION DIVISION.
PROGRAM-ID. rate-lookup.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 rate-values.
   05 FILLER PIC X(10) VALUE "BRL0005250".
   05 FILLER PIC X(10) VALUE "EUR0000920".
   05 FILLER PIC X(10) VALUE "GHS0012300".
   05 FILLER PIC X(10) VALUE "INR0083100".
   05 FILLER PIC X(10) VALUE "JPY0149500".
   05 FILLER PIC X(10) VALUE "KES0129000".
   05 FILLER PIC X(10) VALUE "MXN0017200".
01 rate-table REDEFINES rate-values.
   05 rate-entry OCCURS 7 TIMES
         ASCENDING KEY IS rate-code
         INDEXED BY ri.
      10 rate-code      PIC X(3).
      10 units-per-usd  PIC 9(4)V999.
01 wanted               PIC X(3).
01 usd-amount           PIC 9(5)V99 VALUE 250.00.
01 converted            PIC 9(9)V99.
01 converted-out        PIC ZZZ,ZZZ,ZZ9.99.
01 position-out         PIC 9.
PROCEDURE DIVISION.
0000-main.
    MOVE "INR" TO wanted   PERFORM 1000-convert-binary
    MOVE "KES" TO wanted   PERFORM 1000-convert-binary
    MOVE "CHF" TO wanted   PERFORM 1000-convert-binary
    MOVE "GHS" TO wanted   PERFORM 2000-find-linear
    STOP RUN.

1000-convert-binary.
    SEARCH ALL rate-entry
        AT END
            DISPLAY wanted ": no rate on file"
        WHEN rate-code(ri) = wanted
            COMPUTE converted ROUNDED = usd-amount * units-per-usd(ri)
            MOVE converted TO converted-out
            DISPLAY "250.00 USD = " converted-out " " wanted
    END-SEARCH.

2000-find-linear.
    SET ri TO 1
    SEARCH rate-entry
        AT END
            DISPLAY wanted ": not found"
        WHEN rate-code(ri) = wanted
            SET position-out TO ri
            DISPLAY wanted " is entry " position-out " of the table"
    END-SEARCH.
text
250.00 USD =      20,775.00 INR
250.00 USD =      32,250.00 KES
CHF: no rate on file
GHS is entry 3 of the table

Notice the differences. SEARCH ALL sets the index itself; you must not. Its WHEN may only test the key for equality (combined with AND if there are several keys). SEARCH starts wherever the index already points, which is why 2000-find-linear begins with SET ri TO 1; forgetting that line is a classic bug when the same table is searched twice. SET position-out TO ri converts the index into an ordinary number for display.

If the data were not in ascending order of rate-code, SEARCH ALL would not complain: it would just miss entries. When a table is loaded from a file, sort the file first or check the order as you load. COBOL 2002 also added a SORT statement for tables (SORT rate-entry ASCENDING rate-code), which GnuCOBOL supports.

The out-of-range subscript

Nothing in the language stops you from writing rain-mm(13). By default, most compilers generate no check, so element 13 simply means "the four bytes after element 12", which belong to some other field. Reading it returns garbage; writing it silently corrupts a neighbouring field, and the symptom may appear far from the cause. While developing, compile with run-time checks switched on: cobc -debug (or the narrower -fec=EC-BOUND-SUBSCRIPT) in GnuCOBOL, the SSRANGE option on IBM's compiler. Many shops leave such checks on in production too, judging the small cost worth it.

ComputationC

Taking text apart and putting it together

UNSTRING and STRING

UNSTRING splits a field at delimiters into several receiving fields. STRING does the reverse: it copies pieces into one field, one after another. Here both work on a line of comma-separated data, the kind of export every business system produces:

cobol
IDENTIFICATION DIVISION.
PROGRAM-ID. csv-and-names.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 csv-line           PIC X(60)
       VALUE "1047,Sipho,Ndlovu,Durban,2350.75".
01 emp-id             PIC X(6).
01 first-name         PIC X(15).
01 last-name          PIC X(15).
01 emp-city           PIC X(15).
01 salary-text        PIC X(12).
01 salary             PIC 9(7)V99.
01 field-count        PIC 99 VALUE 0.
01 first-length       PIC 99.
01 report-line        PIC X(50).
01 line-pointer       PIC 99.
01 salary-out         PIC ZZZ,ZZ9.99.
PROCEDURE DIVISION.
    UNSTRING csv-line DELIMITED BY ","
        INTO emp-id
             first-name COUNT IN first-length
             last-name
             emp-city
             salary-text
        TALLYING IN field-count
    END-UNSTRING
    DISPLAY "fields found: " field-count
    DISPLAY "first name has " first-length " letters"
    COMPUTE salary = FUNCTION NUMVAL(salary-text)
    MOVE salary TO salary-out

    MOVE SPACES TO report-line
    MOVE 1 TO line-pointer
    STRING last-name  DELIMITED BY SPACE
           ", "       DELIMITED BY SIZE
           first-name DELIMITED BY SPACE
           " ("       DELIMITED BY SIZE
           emp-city   DELIMITED BY SPACE
           ")"        DELIMITED BY SIZE
        INTO report-line
        WITH POINTER line-pointer
        ON OVERFLOW DISPLAY "line too long"
    END-STRING
    DISPLAY "[" report-line "]"
    DISPLAY "next free position: " line-pointer
    MOVE salary-out TO report-line(line-pointer + 1:)
    DISPLAY "[" report-line "]"
    STOP RUN.
text
fields found: 05
first name has 05 letters
[Ndlovu, Sipho (Durban)                            ]
next free position: 23
[Ndlovu, Sipho (Durban)   2,350.75                 ]

What each clause did:

  • DELIMITED BY "," split the line at commas. Each piece went to the next INTO field, padded with spaces like a MOVE.
  • COUNT IN first-length recorded how many characters went into first-name (5), before padding.
  • TALLYING IN field-count counted the fields filled. It adds to the counter, which is why field-count starts at zero.
  • FUNCTION NUMVAL turned the text 2350.75 into a number. Use NUMVAL-C for text with currency signs and thousands separators.
  • In STRING, DELIMITED BY SPACE copies a field up to its first space, which trims the padding. DELIMITED BY SIZE copies the whole item.
  • WITH POINTER tracks where the next character goes; after the STRING it points just past the last character written, so the program can carry on writing from there. Here a reference-modified move puts the salary one position later.
  • ON OVERFLOW runs if the target fills up before all pieces are copied.

Two traps hide in this example. STRING does not clear its target: whatever was in report-line beyond the copied text stays there, which is why the program moves spaces to it first. And DELIMITED BY SPACE stops at the first space, so a name like Ana Maria would be cut to Ana. For data that can contain spaces, use FUNCTION TRIM or delimit by two spaces instead.

Reference modification, INSPECT and intrinsic functions

Reference modification field(start:length) addresses any slice of a field, read or write; leave out the length to mean "to the end". INSPECT counts (TALLYING), replaces (REPLACING) and translates (CONVERTING) characters in place. And a library of intrinsic functions, called with FUNCTION name(...), covers common text jobs.

cobol
IDENTIFICATION DIVISION.
PROGRAM-ID. inspect-demo.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 card-number        PIC X(16) VALUE "4111222233334444".
01 masked-card        PIC X(16).
01 phone              PIC X(20) VALUE "+351 (21) 555-0199".
01 digit-count        PIC 99 VALUE 0.
01 town               PIC X(20) VALUE "  san josé del cabo".
01 code-in            PIC X(8)  VALUE "ab-12/cd".
PROCEDURE DIVISION.
    MOVE card-number TO masked-card
    INSPECT masked-card(1:12) REPLACING CHARACTERS BY "*"
    DISPLAY "card:   " masked-card

    INSPECT phone TALLYING digit-count FOR ALL "0" "1" "2" "3" "4"
                                               "5" "6" "7" "8" "9"
    INSPECT phone REPLACING ALL "(" BY SPACE ALL ")" BY SPACE
    DISPLAY "phone:  " phone " has " digit-count " digits"

    INSPECT code-in CONVERTING "abcdefghijklmnopqrstuvwxyz-/"
                            TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ.."
    DISPLAY "code:   " code-in

    DISPLAY "town:   [" FUNCTION TRIM(town) "]"
    DISPLAY "upper:  [" FUNCTION UPPER-CASE(FUNCTION TRIM(town)) "]"
    DISPLAY "length: " FUNCTION LENGTH(FUNCTION TRIM(town))
    DISPLAY "slice:  " town(3:3)
    STOP RUN.
text
card:   ************4444
phone:  +351  21  555-0199   has 12 digits
code:   AB.12.CD
town:   [san josé del cabo]
upper:  [SAN JOSé DEL CABO]
length: 000000018
slice:  san
  • Masking a card number is a single INSPECT on a slice: REPLACING CHARACTERS BY "*" replaces every character of the first twelve positions. Payment-industry rules forbid printing full card numbers, and this is how many COBOL systems comply.
  • Counting digits uses TALLYING ... FOR ALL with a list of literals. FOR LEADING and FOR CHARACTERS BEFORE INITIAL "x" are other forms.
  • CONVERTING maps each character of the first string to the character in the same position of the second: here lower case to upper case and - and / to ..
  • TRIM, UPPER-CASE, LENGTH do what their names say. TRIM takes LEADING or TRAILING to trim one side only.

Now look closely at the last three lines of output. UPPER-CASE capitalised every letter except é, and LENGTH reports 18 for a 17-letter name. The reason is that a PIC X field is a sequence of bytes, and this source file is UTF-8, in which é takes two bytes. Classic COBOL text handling is byte-based and assumes a single-byte character set such as EBCDIC or Latin-1. For international text, the standard provides national data, PIC N or USAGE NATIONAL, which IBM's compiler stores as UTF-16, along with functions such as NATIONAL-OF and DISPLAY-OF to convert. If your data includes names from many languages, and in most countries it does, find out early how the system stores them.

ExplanationH

Tables and text in professional code

A few practices separate production code from classroom examples.

Load reference tables from files, not from source code. The REDEFINES-over-FILLER idiom is fine for month names, which never change. Tax bands, exchange rates and product codes do change, so real systems read them from a file or a database table at the start of the run into an OCCURS DEPENDING ON table, check that they arrived in key order, and fail clearly if the table overflows its maximum size. A table that silently stops loading at entry 500 because the maximum was set in 1997 is a famous kind of production incident.

Validate text before converting it. FUNCTION NUMVAL on text that is not a valid number gives an unhelpful result. The function TEST-NUMVAL (COBOL 2014, supported by GnuCOBOL and IBM's compiler) returns 0 when the text is valid and otherwise the position of the first bad character, so a program can reject a record with a precise message.

Know the limits of UNSTRING. Splitting on commas works until a field itself contains a comma, which real CSV files handle with quotes ("Ndlovu, Sipho"). UNSTRING knows nothing about quotes. Either agree on a delimiter that cannot occur in the data (many interfaces use | or fixed-width records for exactly this reason) or write a small character-by-character parser.

Use the newer interchange statements where you have them. Modern IBM Enterprise COBOL can turn a group item into JSON or XML and back with JSON GENERATE, JSON PARSE, XML GENERATE and XML PARSE, which is how many mainframe programs now talk to web services. GnuCOBOL 3.2 recognises the XML and JSON statements but needs optional libraries to run them, which the build used for this course does not include.

Common misconceptionsH

Common misconceptions

Misconception

"Subscripts start at zero." In COBOL they start at 1. month-name(0) is outside the table, and so is month-name(13). Without bounds checking, both silently read other storage.

Misconception

"SEARCH ALL works on any table." It needs a KEY clause and data that is really in key order. On unsorted data it returns "not found" for entries that are there, without any error.

Misconception

"STRING replaces the contents of its target." It writes only the characters it copies and leaves the rest of the target untouched. Clear the target first, or use the pointer to know where the new text ends.

Misconception

"A PIC X(20) field holds twenty letters." It holds twenty bytes. In UTF-8 many letters (é, ñ, ş, and every character of most non-Latin scripts) need two to four bytes, so a twenty-byte field may hold far fewer letters, and slicing it can split a character in half.

Exercises

Exercises

Try each question before opening the hints. Every answer about program output was checked by compiling and running the program with GnuCOBOL 3.2.

1. Tables and strings

Warm-upComputational

iso-date is PIC X(10) VALUE "2026-11-19", and y, m and d are PIC X(4), PIC X(2) and PIC X(2). What does this print?

    UNSTRING iso-date DELIMITED BY "-" INTO y m d END-UNSTRING
    DISPLAY d "/" m "/" y

2. Tables and strings

CoreComputational

full-name is PIC X(20) VALUE "Ana Maria" and out-line is PIC X(20) VALUE SPACES. What does this print?

    STRING full-name DELIMITED BY SPACE
           "!"       DELIMITED BY SIZE
        INTO out-line
    END-STRING
    DISPLAY "[" FUNCTION TRIM(out-line) "]"

3. Tables and strings

Warm-upComputational

river is PIC X(11) VALUE "Mississippi" and n is PIC 99 VALUE 0. After INSPECT river TALLYING n FOR ALL "ss", what is n?

4. Tables and strings

Warm-upComputational

mountain is PIC X(11) VALUE "Kilimanjaro". What does DISPLAY mountain(5:4) print?

5. Tables and strings

CoreHuman

What does SEARCH ALL need in order to work correctly? Choose all that apply.

Choose all that apply

6. Tables and strings

StretchComputational

The source file is UTF-8, and city is PIC X(15) VALUE " São Paulo". What does DISPLAY FUNCTION LENGTH(FUNCTION TRIM(city)) show, as a number?

7. Tables and strings

CoreHuman

A table is declared 05 rate OCCURS 10 TIMES PIC 9V99. and a program executes MOVE 1.50 TO rate(11), compiled with default options. What is the most likely outcome?

Choose one

Further reading and resources