COBOL by Example: String Handling
Manipulating strings with STRING for concatenation, UNSTRING for splitting text by delimiters, INSPECT for counting and replacing characters, handling fixed-width fields with DELIMITED BY clauses, and formatting data for reports.
Code
IDENTIFICATION DIVISION.
PROGRAM-ID. STRINGS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 F-NAME PIC X(10) VALUE "John".
01 L-NAME PIC X(10) VALUE "Doe".
01 FULL-NAME PIC X(30) VALUE SPACES.
01 SENTENCE PIC X(50) VALUE "COBOL IS FUN".
01 COUNT-O PIC 99 VALUE 0.
PROCEDURE DIVISION.
*> Concatenation
STRING F-NAME DELIMITED BY SPACE
" " DELIMITED BY SIZE
L-NAME DELIMITED BY SPACE
INTO FULL-NAME.
DISPLAY "Full Name: " FULL-NAME.
*> Counting characters
INSPECT SENTENCE TALLYING COUNT-O FOR ALL "O".
DISPLAY "Count of 'O': " COUNT-O.
*> Replacing characters
INSPECT SENTENCE REPLACING ALL "FUN" BY "COOL".
DISPLAY "New Sentence: " SENTENCE.
STOP RUN.Explanation
COBOL provides specialized verbs for string processing that are powerful and efficient. The STRING verb concatenates multiple strings into one, handling delimiters automatically. The UNSTRING verb does the reverse, parsing a string into multiple fields.
The INSPECT verb is a workhorse for string validation and manipulation. It can count occurrences of a character (TALLYING) or replace characters (REPLACING). This is often used to sanitize input or format data for output.
These verbs operate on fixed-length buffers, so you often use the DELIMITED BY clause to ignore trailing spaces. This is a common pattern in COBOL, where string variables are typically fixed-width fields padded with spaces.
STRING: Concatenates multiple strings into one.UNSTRING: Splits a string into multiple parts based on delimiters.INSPECT: Used for counting occurrences or replacing characters.

