Coding Cobol: A note on strings

There are two types of string in Cobol, and they are very different. The first type of string is one that treats the entity created as en entire entity, i.e. it is not possible to index this type of string. These strings were created in Cobol to store things like peoples names etc. and Cobol provides a lot of functionality to process them, they are just not able to be subscripted because they are not arrays. Here is an example of a program that reads in a 10-character entity, and tries to print it out by elements.

identification division.
program-id. strings.

data division.
working-storage section.
01 str1 pic x(10).
77 i pic 99.

procedure division.
    accept str1.
    perform varying i from 1 by 1 until i=10
       display str1(i)
    end-perform.
stop run.

When compiled, this will produce the error message: “error: ‘str1' cannot be subscripted“. It can be subscripted because it is a string, but it can be sub-stringed using str(i:x), where x represents the length of the substring, x=1 for a single element), as noted in the comments.

In order to create a string that can be subscripted, you need an array of characters (or rather a table as an array is known in Cobol). Below is the same example as above using an array.

identification division.
program-id. strings.

data division.
working-storage section.
01 str-arr.
   03 str2 pic x occurs 10 times.
77 i pic 99.

procedure division.
    accept str-arr.
    display str-arr.
    perform varying i from 1 by 1 until i=11
       display str2(i)
    end-perform.

stop run.

Notice two things. One, that the array is created with both a “global” name, str-arr (line6), and a indexed name, str2 (line 7). The use of str-arr allows for the array of characters to be read in as a whole, rather than having to use a loop (line 11) – and also output as a whole entity (line 12). If you want to index the array, then you can use str2, as shown in the loop in lines 13-15. The input and output from the above code is shown below:

photograph
photograph
p
h
o
t
o
g
r
a
p
h

One thought on “Coding Cobol: A note on strings

  1. datagubbe says:

    Subscripting strings must be done by supplying both start and length, E.G. str1(i:1) would work in the first example.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.