compute length string of variable with cobol
cobol
Solution
Here's a common way:
MOVE ZERO TO count-of-trailing-spaces
INSPECT FUNCTION REVERSE ( NOTE-TEXT )
TALLYING count-of-trailing-spaces
FOR LEADING SPACE
SUBTRACT count-of-trailing-spaces
FROM LENGTH OF ( NOTE-TEXT )
GIVING NOTE-LEN
`FUNCTION REVERSE` will swap the bytes of a field into reverse order. `INSPECT` does not have `TALLYING ... TRAILING` (except in compilers from some vendors, but it is non-standard) so `INSPECT ... LEADING ...` can be used once the field is reversed.
Sometimes I should take my irony hat off. If using the `FUNCTION REVERSE`, also check the field for space first, there is no point in reversing 500 spaces and then counting 500 leading spaces.
Also "know your data". If notes are mostly short, and you do a lot of them, you might want to investigate whether something more speedy is required. It depends on your data and hardware as to whether there's a benefit to be had from that, but bear it in mind.
It may be worth investigating whether something up the line actually knows how long the field is, and can already tell you.
I'd just loop from the back, counting spaces (after first checking for all space). Less strain on the CPU. One way to do that:
IF NOTE-TEXT EQUAL TO SPACE
MOVE ZERO TO NOTE-LEN
ELSE
MOVE LENGTH OF NOTE-TEXT TO NOTE-LEN
PERFORM
UNTIL NOTE-TEXT-BYTE ( NOTE-LEN )
NOT EQUAL TO SPACE
SUBTRACT +1 FROM NOTE-LEN
END-PERFORM
END-IF
Of course this requires a defintion of `NOTE-TEXT-BYTE` as being a constituent of `NOTE-TEXT`.
The 49-level is probably significant, so can't do it so neatly:
49 NOTE-TEXT PIC X(500).
49 NOTE-TEXT-BYTE
REDEFINES NOTE-TEXT
OCCURS 500 PIC X.
Perhaps the 49s provide some case for reference-modification. Perhaps not.
Problem
I have a NOTE in database table How can i calculate the length of that string? I have a variable defined like ``` 10 NOTE. 49 NOTE-LEN PIC S9(4) USAGE COMP. 49 NOTE-TEXT PIC X(500). ``` Note is a string of 500 characters. I want to compute the note length.