Alphanumeric fields (strings)
Declaring text
Text lives in PIC X fields. The size in parentheses sets the exact length, and the field always holds that many characters, padded with spaces on the right.
01 WS-GREETING PIC X(30) VALUE "Hello".
01 WS-LETTER PIC X.
Moving text
MOVE copies fields character by character. A shorter source pads with spaces; a longer source is truncated on the right. MOVE CORRESPONDING moves matching names between groups:
MOVE "COBOL" TO WS-GREETING.
MOVE WS-FIRST-NAME TO WS-LAST-NAME.
Trimming spaces
Fixed-length fields keep trailing spaces, which shows up in reports and file output. Inspect with TALLYING counts characters, and STRING with delimiters rebuilds clean values:
INSPECT WS-GREETING TALLYING WS-N FOR TRAILING SPACES.
The code on this page was run with GnuCOBOL 3.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev