Scanning and Replacing Occurrences of a Character

Article ID: 16960

Q: How do I scan a string in RPG and replace all occurrences of a character?

A: There is a built-in function to scan a string and another to replace a character, but there is no equivalent of the scan-and-replace feature of editors and word processors. You can create a simple routine to accomplish it though, as shown below:

     H*Program Name: TestScan
     H*Title: Scan a string and replace all single quotes with two
     H*       single quotes.
     H*       Display original and changed strings.
     D
     D Source          S             25    Inz('''abc''de''fghi')
     D Target          S             50
     D Temp            S             25
     D Start           S              3  0
     D PosFnd          S              3  0
     D Size            S              3  0
     D End             S              3  0
     D Quote           S              1    Inz('''')
     D
     C
     C* Find total Length of characters in Source string:
     C                   Eval      End = %Len(%Trim(Source))
     C
     C                   Eval      Start = 1
     C* Loop until no single quotes found:
     C                   DoU       PosFnd = 0
     C* Find single quotes in string:
     C     Quote         Scan      Source:Start  PosFnd
     C                   If        *IN02
     C* Determine size of string since last single quote found:
     C                   Eval      Size= (PosFnd - Start) + 1
     c                   Eval      size = -1
     C     Size          Subst (P) Source:Start  Temp
     C                   Eval      Target = %Trim(Target)
     C                               + %Trim(Temp) + Quote
     C                   Eval      Start = PosFnd + 1
     C                   EndIf
     C                   EndDo
     C
     C* If any Source string left after last quote found, 
     C* move to Target:
     C                   If        Start < End
     C                   Eval      Size= End - Start + 1
     C     Size          Subst (P) Source:Start  Temp
     C                   Eval      Target = %Trim(Target)
     C                               + %Trim(Temp)
     C                   EndIf
     C
     C     Source        Dsply
     C     Target        Dsply
     C
     C                   Eval      *INLR =*On

The above appears as an IBM FAQ at http://www.developer.ibm.com/tech/faq/individual/0,1324,1%253A317%253A318%253A10%253A80635,00.html.

ProVIP Sponsors

ProVIP Sponsors