Blog Archive

RPGLE string manipulation - Insert a String using %replace() and %scan()

Click here if you are looking for Find and Replace


%REPLACE returns the character string produced by inserting a replacement string into the source string, starting at the start position and replacing the specified number of characters.


%REPLACE(replacement string: source string{:start position {:source
length to replace}})

%SCAN returns the first position of the search argument in the source string, or 0 if it was not found. If the start position is specified, the search begins at the starting position. The result is always the position in the source string even if the starting position is specified. The starting position defaults to 1.


%SCAN(search argument : source string {: start})

Insert a String

One often-overlooked capability of %REPLACE is its ability to insert a string.  Just set the length to delete to 0, the %REPLACE BIF won't delete any text from your string. Instead, it just inserts the data right before the position you specified.
$pos = %scan(%trim($scan_data):$string_data);    
$string_data = %replace( %trim($replace_data)      
                   : $string_data                  
                   : $pos                          
                   : 0);