Creating your own left-pad and right-pad string functions
A. A Missing Piece
Somewhat surprisingly, PeopleCode does not provide a native ‘lpad’ or ‘rpad’ function. These functions typically appear in programming languages to allow a string to be padded out to a certain number of characters. The ‘lpad’ function works by adding extra characters on the left-hand side of the string, while ‘rpad’ works on the right-hand side. The extra character is often a space by default, but this can be changed to any other character. Fortunately, by using the ‘Rept’ function, a workaround can be achieved.
B. Rept Function
The ‘Rept’ function simply repeats the supplied string a certain number of times:
&string = Rept("a", 5);
This will produce ‘aaaaa’.
The string passed to the ‘Rept’ function need not be a single character:
&string = Rept("abc", 3);
This will produce the string ‘abcabcabc’.
C. Using Repeat to Perform a LPad or RPad
By using the ‘Rept’ function in combination with the ‘Len’ function – to return a string length – you can now perform an lpad-like function. The following example left-pads a string with the ‘0’ character to a maximum of ten places:
If Len(&string) < 10 Then &string = Rept("0", 10 - Len(&string)) | &string; End-If;
Here is the equivalent ‘rpad’ version:
If Len(&string) < 10 Then &string = &string | Rept("0", 10 - Len(&string)); End-If;
Rather than hard-code the parameters directly into the code, a better option would be to create a lpad and rpad function:
Function lpad(&in_string As string, &length As number, &pad_char As string) Returns string If Len(&in_string) < &length Then &in_string = Rept(&pad_char, &length - Len(&in_string)) | &in_string; End-If; Return &in_string; End-Function; Function rpad(&in_string As string, &length As number, &pad_char As string) Returns string If Len(&in_string) < &length Then &in_string = &in_string | Rept(&pad_char, &length - Len(&in_string)); End-If; Return &in_string; End-Function;
Now you can call the lpad function directly. The following example produces a result of ‘0000000123’:
&num_char = "123"; &num_char = lpad(&num_char, 10, "0");
If your source string is always going to be a numeric value, another possible option is the ‘NumberToString’ function. Refer to Tip 053 for more details.
Tip 053: Function NumberToString