Tips and Techniques: Trim Leading and Trailing Characters as Well as Blanks

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

In OS/400 V3R1, IBM introduced the %TRIM, %TRIML, and %TRIMR built-in functions. Effectively, these built-in functions delete trailing and/or leading blanks from a field and return a copy of the data without the trailing/leading blanks.

  • %TRIM deletes both trailing and leading blanks from a field and returns that value to the expression in which %TRIM is being used.
  • %TRIML deletes leading blanks (left side) from a field and returns the value to the expression in which %TRIML is being used.
  • %TRIM deletes trailing blanks (right side) from a field and returns the value to the expression in which %TRIMR is being used.

It would have been a lot more difficult to do certain things in RPG IV without these three built-in functions.

Nearly 10 years after RPG IV was announced and the trim functions were introduced, OS/400 V5R3 was announced, and it came with a second parameter for the trim functions. This new, second parameter allows you to identify specific characters you want to remove from the field. Whatever you specify for the second parameter is deleted from the field. As with the original trim functions, only the trailing or beginning characters are deleted, not those in the middle of the field.

Here's the new syntax:

%TRIMx( string-value  [ :  'trim-characters'] )

%TRIMx allows you to specify whether you want the characters removed from the beginning, the end, or both (%TRIML, %TRIMR, or %TRIM, respectively). The string-value parameter may be a field (including an array element), literal, named constant, or character-string expression. The optional trim-characters parameter may be one or more characters.

Remember, this enhancement only works on V5R3 or later, which means it is unavailable to virtually everyone as of this writing. Sorry. Cool idea, though. If you want to do this today, you can use the TRIML and TRIMR subprocedure that I wrote about in a previous issue. Then, when you move to V5R3, simply do a scan/replace by adding the % prefix to the subprocedure names. Or better yet, code this:

      /IF DEFINED(*V5R3M0)
     C                   eval      myVal = %TRIMR(CustName:' ."')
     C                   eval      myVal = TRIMR(CustName:' ."')

By using precompiler directives, you can prepare your code to use the contemporary features when they become available. Until then, you code a workaround that performs the equivalent routine.

Now get back to work!

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.