Search code examples
arraysstringvariablescobol

How to get a single character from a string in COBOL?


For example if a string is "work" I have to access 3rd character and store it. In C one would do:

char data[5] = "work";
char temp = data[2];

Variable temp will have the value 'r'. Now I need to achieve an equivalent in COBOL.


Solution

  • The first thing to understand is that array indices are zero based in C and 1 based in COBOL.

    Next COBOL and C have very differnt ways of representing character strings. In C a string is generally stored as an array of characters, the end of string is typically represented using a binary zero (null \0). COBOL has no such convention. Strings are stored in named data items of a specified length. These items are typically declared under WORKING-STORAGE and have a PICTURE Clause associated with them of type 'X' (there are several other possibilities for PICTURE clauses but 'X' represents any type of character). For example:

    01    MY-VARIABLE   PIC X(20).
    

    The Working Storage variable called MY-VARIABLE is declared as 20 characters long. It may be assigned a value in the PROCEDURE DIVISION as follows.

    MOVE 'work' TO MY-VARIABLE
    

    You can then access the various characters of this string (or substrings) using a technique known as reference modification:

    DISPLAY MY-VARIABLE(3:1)
    

    will display the third character of MY-VARIABLE (1 based indexing), which is 'r'. The first number in parenthesis above (3) indicates the offset from the beginning of the variable, the second number is the number of characters starting from that position (1).

    There are other methods of doing this, such as REDEFINES, where MY-VARIABLE could be redefined as an array of 20 1 character cells. This is a somewhat outdated mechanism so I would encourage using reference modification to access parts of character strings.