4

How do I concatenate together two strings, of unknown length, in COBOL? So for example:

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

If FIRST-NAME = 'JOHN ' and LAST-NAME = 'DOE ', how can I get:

FULL-NAME = 'JOHN DOE                       '

as opposed to:

FULL-NAME = 'JOHN            DOE            '
2
  • @badp the point of the b's to show blanks is so that we can count the blamed things. Why did you change them? Jun 8, 2015 at 21:24
  • Do you need to count to know they pad each string to 15 chars? (Can there even be a difference in COBOL between 'foo' and 'foo '?)
    – badp
    Jun 8, 2015 at 21:58

3 Answers 3

5

I believe the following will give you what you desire.

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

At first glance, the solution is to use reference modification to STRING together the two strings, including the space. The problem is that you must know how many trailing spaces are present in FIRST-NAME, otherwise you'll produce something like 'JOHNbbbbbbbbbbbbDOE', where b is a space.

There's no intrinsic COBOL function to determine the number of trailing spaces in a string, but there is one to determine the number of leading spaces in a string. Therefore, the fastest way, as far as I can tell, is to reverse the first name, find the number of leading spaces, and use reference modification to string together the first and last names.

You'll have to add these fields to working storage:

WORK-FIELD        PIC X(15) VALUE SPACES.
TRAILING-SPACES   PIC 9(3)  VALUE ZERO.
FIELD-LENGTH      PIC 9(3)  VALUE ZERO.
  1. Reverse the FIRST-NAME
    • MOVE FUNCTION REVERSE (FIRST-NAME) TO WORK-FIELD.
    • WORK-FIELD now contains leading spaces, instead of trailing spaces.
  2. Find the number of trailing spaces in FIRST-NAME
    • INSPECT WORK-FIELD TALLYING TRAILING-SPACES FOR LEADING SPACES.
    • TRAILING-SPACE now contains the number of trailing spaces in FIRST-NAME.
  3. Find the length of the FIRST-NAME field
    • COMPUTE FIELD-LENGTH = FUNCTION LENGTH (FIRST-NAME).
  4. Concatenate the two strings together.
    • STRING FIRST-NAME (1:FIELD-LENGTH – TRAILING-SPACES) “ “ LAST-NAME DELIMITED BY SIZE, INTO FULL-NAME.
1
  • "fastest" is an odd way to describe it, but it at least deals with embedded spaces correctly. Jan 21, 2013 at 7:36
0

You could try making a loop for to get the real length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.