How to get the length of character type variable in RPGLE?

13.5k Views Asked by At

Is there any easy way to directly return the length of character and type variable in RPGLE? The length I am talking about here is not the length specified in the D-spec. I am talking about the actual number of meaningful characters in a string. Let's say a character type variable is defined to be 50 characters long, and it is assigned with value 'Hello world!', then the length I want is 12, which is from 'H' to '!'. The leading and trailing blank is ignored. Is there any simple way to do this?

2

There are 2 best solutions below

0
On

You can use %len(%trimr(field)), which trims trailing spaces before checking the length.

  • %triml trims leading spaces (on the left)
  • %trimr trims trailing spaces (on the right)
  • %trim trims leading and trailing spaces
0
On

It looks like the field you are trying to find the length of is a fixed character field, like

     dmsg              s             40a

If we do an eval msg = 'Hello, World!' then msg does not contain 'Hello, World!' - it contains 'Hello, World! ' That is, it has a pile of blanks to pad it out to 40 characters. That's how fixed length fields work by definition.

%trimr() can work very well with these, and it even has an optional parameter to define which characters should be trimmed.

On the other hand, if you were to use a varying length field

     dmsg              s             40a   Varying

and then did an eval msg = 'Hello, World!' then the field actually contains only the characters assigned to it. In this case, no %trimr() is needed; %len() will return the current length of the field.