๐ŸŽ‰ Active offers RPG10 First lesson is FREE! โ€ข RPG25 25% off the full series โ€ข
ILERPG.com โ€” IBM i ยท ILE RPG ยท AS400 Mastery
2 min readยท Admin

Five String Functions That Clean Up Real-World Data in ILE RPG

A field declaration describes storage. It says nothing about what actually arrives in it. Part numbers come in lower case, names arrive as one field that needs splitting, account numbers need masking before display. A handful of built-in functions handles nearly all of it.

%LEN measures โ€” and can truncate

%LEN returns a string's current length: the declared size for CHAR, the stored length for VARCHAR. It can also be an assignment target. Assigning to %LEN on a VARCHAR field shortens the stored value directly, which is a fast way to enforce a maximum length on incoming data.

%SUBST extracts โ€” and can overwrite

%SUBST(string : start : length) returns part of a string using 1-based positions. On the left of an assignment it overwrites a fixed-width portion in place, leaving everything else where it was.

%SCAN finds โ€” or returns zero

%SCAN returns the position of a search string, or 0 when it is absent. That zero is a routine outcome, not an edge case. Passing it unchecked into %SUBST as a start position produces a runtime error the first time the delimiter is missing โ€” usually in production.

commaPos = %scan(',' : custLine);
if commaPos = 0;
  // handle an unsplit name
else;
  lastName  = %subst(custLine : 1 : commaPos - 1);
  firstName = %subst(custLine : commaPos + 1);
endif;

%REPLACE inserts or overwrites

With a length, %REPLACE removes that many characters and puts the replacement in their place โ€” ideal for masking. Without a length, it inserts without removing anything. Unlike %SUBST as a target, the replacement need not match the length of what it displaces.

%TRIML, %TRIMR, and %XLATE

%TRIML and %TRIMR remove blanks from one side only, which is more precise than %TRIM when the padding is known to be one-sided. %XLATE performs a character-by-character lookup and swap โ€” the standard approach to case conversion โ€” and leaves every character outside its comparand untouched.

Lesson 18 combines all of these in a routine that normalizes incoming product codes.

Get the lesson

Lesson 18, โ€œBuilt-In Functions Part 1: String Manipulation,โ€ is part of Beginner ILE RPG in IBM i ILE RPG Mastery and is available at ILERPG.com for USD 10. The complete Beginner ILE RPG series โ€” all 18 lessons โ€” is USD 180, or USD 135 with coupon code RPG30, which takes 25% off when you purchase the full series.