Programming Fundamentals/Strings/COBOL

strings.cbl

edit
*> This program splits a given comma-separated name into first and last
*> name components and then displays the name.
*>
*> References:
*>     https://www.tutorialspoint.com/cobol/index.htm
*>     https://open-cobol.sourceforge.io/doc/gnucobol.html

IDENTIFICATION DIVISION.
PROGRAM-ID. STRINGS.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 NAME-IN          PIC X(25).
01 FIRST-NAME       PIC X(25).
01 LAST-NAME        PIC X(25).
01 LEADING-SPACES   PIC X(25).
01 NAME-OUT         PIC X(50).
01 NAME-POINTER     PIC 9(2).

PROCEDURE DIVISION.

MAIN.
    PERFORM GET-NAME.
    PERFORM SPLIT-NAME.
    PERFORM DISPLAY-NAME.
    STOP RUN.

GET-NAME.
    DISPLAY "Enter name (last, first):"
    ACCEPT NAME-IN.

SPLIT-NAME.
    UNSTRING
        NAME-IN DELIMITED BY ","
        INTO LAST-NAME, FIRST-NAME
    END-UNSTRING.

    UNSTRING
        FIRST-NAME DELIMITED BY ALL SPACES
        INTO LEADING-SPACES, FIRST-NAME
    END-UNSTRING.

    UNSTRING
        LAST-NAME DELIMITED BY ALL SPACES
        INTO LEADING-SPACES, LAST-NAME
    END-UNSTRING.

DISPLAY-NAME.
    MOVE SPACES TO NAME-OUT.
    MOVE 1 TO NAME-POINTER.
    STRING
        "Hello " DELIMITED BY SIZE
        FIRST-NAME DELIMITED BY SPACE
        " " DELIMITED BY SIZE
        LAST-NAME DELIMITED BY SPACE
        "!" DELIMITED BY SIZE
        INTO NAME-OUT
        WITH POINTER NAME-POINTER
    END-STRING.
    DISPLAY NAME-OUT.

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own COBOL compiler / interpreter / IDE.

See Also

edit