How does one automatically read the number of characters in a string in RPGLE? I want to do this so that spaces are not counted, but punctuation and other actual characters are. For example "test" would come back as 4 characters, while "test underway" would read as 12 and "test underway!" would read as 13.

Asked:
Last updated:

## Discuss This Question: 6 Replies

If you are on V7R1, You can use %SCANRPL and replace Blanks with Nulls.

Then you will have all the characters left justified. Now check for the 1st blanks and subtract 1. This will give you the number of characters.

It depends on the definition of "string". There are at least two different kinds: fixed- and varying-length. And it also can depend on the definition of "test", "test underway" and "test underway!"

In general, the length is returned by the %size() function. But that can be incorrect if various definitions change.

As written, the question asks about the lengths of three literal constants. In the three examples given, %size('test') would return a value of (4), %size('test underway') would be (12) and %size('test underway!') would be (13). But those are pointless examples. It's effectively meaningless to code to test the length of literal constants because the lengths are known when developer creates the code.

Instead, we usually test the lengths of variable values. And that means we need to know (1) if the variables are fixed- or variable-length and (2) if leading/trailing spaces, nulls or other character values are significant.

The %size() function is useful, but %len() and %trim() might be needed as well. It all depends on definitions.

Tom

CharlieBrowne's use of %scanrpl() in i 7.1 can compress out all internal spaces in a single operation. Be careful, though, to replace with a zero-length string and not with nulls. But prior to i 7.1, the combination of %replace() and %scan() would be used to compress them out. With those, it's necessary to process each internal space separately, so a loop is needed.

Note that if internal spaces have been compressed out of a varying-length variable or if a fixed-length variable value has no spaces, you can't test for the first space and subtract 1 because the result will be (-1) rather than the actual length. The %size(), %len() and possibly %trim() functions should still be used

Tom