How to subdivide the contents of a string variable based on a certain symbol in the content of the variable in RPGLE

Viewed 365

Suppose I have a string variable in RPGLE . The content of the variable is "Hi;this;is;Kunal;Roy". How do I split the contents of the string based on the symbol ;

I want to have the values Hi , this, is , Kunal , Roy separated and stored in some other variable.

Can someone suggest a easy way of doing it in rpgle.

3 Answers

There are many different ways of dealing with this. One solution would be to use the C function strtok or strtok_r. You could also code your own procedure.

The service programs Linked List and Arraylist (from rpgnextgen.com) both have a split procedure which splits a string and stores the parts in a list. Documentation to both service programs can be found at http://iledocs.rpgnextgen.com .

**FREE

ctl-opt dftactgrp(*no) actgrp(*caller) bnddir('GLOBAL');

/include 'arraylist/arraylist_h.rpgle'

main();
*inlr = *on;


dcl-proc main;
  dcl-s list pointer;
  dcl-s text varchar(50);
  dcl-s part varchar(50);

  text = 'Hi;this;is;Kunal;Roy';
  list = arraylist_split(text);
  part = arraylist_getString(list : 0);
  dsply part;

  arraylist_dispose(list);
end-proc;

You can easily install those service programs with the package manager iPKG from the repo at https://repo.rpgnextgen.com .

This is a really good question

You could define an array to fill and then loop over the string

D ArMax           c                    10                                       
D ArVal           S                   dim(ArMax) like($MyString)                

c                   movel     ';'           $Symbol           1                         
c                   z-add     1             $Start            3 0                       
c     *like         define    $Start        $Pos           
c     *like         define    $Start        @@count        
       $MyString = 'Hi;this;is;Kunal;Roy';                                              
       $pos = %scan($Symbol: $MyString:$start);                                             
       dow $pos > 0;                                                                    
         @@count = @@count +1;                                                                                                                                                    
         ArVal(@@Count) = %subst($MyString:$Start:$pos-$Start);                         
         $start = $pos +1;                                                              
         $pos = %scan($Symbol: $MyString:$Start);                                           
       enddo;                                                                           
Related