In this post, let's see how we can find the exact length of a string in COBOL.
By exact length, I mean not to account the trailing spaces while calculating the length. That's why we can't use FUNCTION-LENGTH because it returns the length which is sum of all the characters in the string plus the trailing spaces.
In the following example, we have a data item, WS-NAME which can accept alphanumeric data upto 100 characters (PIC X(100)) and that's a lot for a name π. FYI, a place in New Zealand holds the Guiness World record for longest place name (85 letters).
Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu π¦ |
Code:
IDENTIFICATION DIVISION.
PROGRAM-ID. LENGTH.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-NAME PIC X(100) VALUE SPACES.
PROCEDURE DIVISION.
MOVE 'Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu' TO WS-NAME.
DISPLAY 'Length is ' FUNCTION LENGTH(WS-NAME).
STOP RUN.
Length is 100
Want to try running this code? Click π here.
Instead of displaying the exact length (85 characters) of the string, FUNCTION-LENGTH has displayed the total length of the data item.
It's clearly evident that we can't rely on FUNCTION-LENGTH if we are given a task of finding and announcing Guiness World Record for a place with longest name (using COBOL).
So what do we do now? π€
The common approach to tackle π§this problem is to reverse the data item (using FUNCTION-REVERSE) containing the place's name and count for the leading spaces (using INSPECT verb). Then, subtract the count of trailing spaces from the total length of the data item.
We have to reverse the string because we can't use INSPECT verb to count for the trailing spaces.
Here is the code π
IDENTIFICATION DIVISION.
PROGRAM-ID. LENGTH.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-NAME PIC X(100) VALUE SPACES.
01 WS-COUNT PIC 9(3) VALUE 0.
01 WS-ACTUAL-LENGTH PIC ZZ9 VALUE 0.
PROCEDURE DIVISION.
MOVE 'Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu' TO WS-NAME.
INSPECT FUNCTION REVERSE(WS-NAME) TALLYING WS-COUNT FOR LEADING SPACE.
SUBTRACT WS-COUNT FROM FUNCTION LENGTH(WS-NAME) GIVING WS-ACTUAL-LENGTH.
DISPLAY 'Length is ' WS-ACTUAL-LENGTH.
STOP RUN.
Length is 85
There you go! This approach works fine even for strings with embedded blanks.
Hope this helps!
And, with this post I've got an intent to start a new series of posts that will be labelled as Interview Questions. You can access all the posts under this label from Labels section in the sidebar.
thx π
Wonderful work
ReplyDeletegreat job...well explained..The best explanation i have found so far .Keep doing and posting more scenario based interview questions for experienced.Thanks
ReplyDelete