IBMi (AS400) fans only - Discover the power of the %SPLIT BIF in RPG
In RPG, we often need to manage strings, split them into substrings, and manipulate them efficiently. The %SPLIT BIF is a powerful and useful tool to handle this task.
But what exactly is %SPLIT? 🤔
%SPLIT
divides a string into multiple parts using a
specified delimiter. It can return an array of values based on the delimiter
you choose, making it easier to handle complex data or composite strings.
Here’s a practical code example to understand it better:
**FREE array = %Split(stringa : delimiter); *inlr = *on; For i = 1 to %Elem(array); |
In this example, the string 'apple,banana,orange' is split
into three elements in the array using a comma as the delimiter. Very simple
and effective!
Here’s a more complex example
with a different delimiter, like the `|` (pipe) character:
**FREE Dcl-s stringa Varchar(200) Inz('A|00013582|1|0|GRAFENE SYMON BOUTIQUE|475, AVENUE VICTOR HERNANDEZ| + 75555|PARIS|FR|51| |FR|123456789012|'); Dcl-s array
Varchar(50) Dim(20); Dcl-s delimiter Varchar(1) Inz('|'); Dcl-s i
Int(10); // Index for the loop // ***************************************************** array = %Split(stringa : delimiter); *inlr = *on; |
In this case, the string is split using the `|` character,
and the extracted data will be:
1. A
2. 00013582
3. 1
4. 0
5. GRAFENE SIMON BOUTIQUE
6. 475, AVENUE VICTOR HERNANDEZ
7. 75555
8. PARIS
9. FR
10. 51
11. (Empty space)
12. FR
13. 123456789012
As you can see, %SPLIT simplifies handling complex strings
and allows you to work with data more efficiently!
Some tips to use it effectively?
What do you think? Have you used %SPLIT in your RPG
projects?
The problem with using a CSV string as an example is that the original version of %SPLIT does not handle this well in the real world. Typical CSVs often include "empty" entires like so: ABC,XYZ,,25,,100
ReplyDelete%SPLIT will not process this correctly as it ignores consective delimiters. So that string returns only 4 elements instead of the 6 that are intended (and as Excel for example would treat it)>
You need to add the new (2023) optional third parameter *ALLSep to have the CSV processed correctly.
Thank you for pointing that out! You're absolutely correct
DeletePersonally, when dealing with CSV files, I prefer using the command `CPYFRMIMPF`.
However, `%SPLIT` with the `*ALLSep` parameter now offers an alternative for those who want to handle such data directly within their RPG code.
Thanks again for your valuable input!
Best,
Aldo
for those who are looking for an alternative to handling CSV files, I have another post on my blog that might interest you. Check out this page
ReplyDeletehttps://rpgfreeibm.blogspot.com/2021/05/how-to-import-csv-file-into-db2.html
where I demonstrate how to use the CPYFRMIMPF command to import a CSV file directly into DB2.