Mastering String Concatenation in COBOL

In the world of programming, dealing with strings is a common task. In COBOL, one might often face the challenge of concatenating strings whose lengths are not predetermined. This article aims to provide a clear solution to the question of how to concatenate two strings of unknown length in COBOL effectively.

The Problem

Imagine you are working with a program that handles a user’s first and last names. Your WORKING-STORAGE section defines variables to store these names, but the challenge arises when you need to concatenate them into a full name without retaining unnecessary spaces. For example, given:

WORKING-STORAGE.
    FIRST-NAME    PIC X(15) VALUE SPACES.
    LAST-NAME     PIC X(15) VALUE SPACES.
    FULL-NAME     PIC X(31) VALUE SPACES.

Assuming FIRST-NAME is set to 'JOHN ' and LAST-NAME to 'DOE ', you seek to achieve the result:

FULL-NAME = 'JOHN DOE                       '.

However, a naive concatenation might lead you to end up with:

FULL-NAME = 'JOHN            DOE            '.

This is not the desired outcome as it includes extra spaces between the concatenated parts. So, how do you solve this issue?

The Solution

The solution to this problem is to use COBOL’s STRING statement effectively. It allows you to concatenate strings and specify delimiters to eliminate unwanted spaces. Below are the steps to concatenate the two strings properly.

Step-by-Step Guide

  1. Define the Strings: Ensure you have defined your FIRST-NAME, LAST-NAME, and FULL-NAME in your WORKING-STORAGE section as illustrated above.

  2. Use the STRING Statement: You can use the STRING statement to concatenate the strings. Here’s how to do it:

    STRING
        FIRST-NAME DELIMITED BY " ",
        " ",
        LAST-NAME DELIMITED BY SIZE
    INTO FULL-NAME.
    

Breakdown of the STRING Statement

  • FIRST-NAME DELIMITED BY " “: This tells COBOL to use FIRST-NAME and stop concatenating at the first space encountered, effectively trimming trailing spaces.

  • ” “: This adds a single space between the first and last names to ensure they are properly separated.

  • LAST-NAME DELIMITED BY SIZE: This specifies that the entire length of the LAST-NAME should be included in the concatenation, thus avoiding unnecessary trailing spaces.

  • INTO FULL-NAME: This directs the resulting concatenated string to be stored in FULL-NAME.

Conclusion

Following these steps, you will be able to efficiently concatenate strings of unknown lengths in COBOL while ensuring a clean and formatted output. By leveraging the STRING statement with appropriate delimiters, COBOL simplifies the process of string management, making it a powerful tool for your programming needs.

Now, next time you face a similar challenge with concatenation in COBOL, you can confidently apply this method to achieve your desired results!