Loading

REXX – STRREPLACE : Replace part of a string with new string

The Below Rexx function STRREPLACE can replace a part of a string with a new one

/*REXX*/
MYSTR = 'MY TEST STRING'
SAY MYSTR
MYSTR = STRREPLACE(MYSTR,'TEST','NEW')
SAY MYSTR
EXIT
/* A FUNCTION TO DO A STRING REPLACE */
STRREPLACE:
ORIGINAL = ARG(1)
OLDTXT = ARG(2)
NEWTXT = ARG(3)
/* YOU CAN CHANGE THE BELOW KEY (TMPTXT), WHICH IS USED AS A TEMPORARY
POINTER TO IDENTIFY THE TEXT TO BE REPLACED */
TMPTXT = '6A53CD2EW1F'
NEWSTR = ORIGINAL
DO WHILE POS(OLDTXT,NEWSTR) > 0
NEWSTR = SUBSTR(NEWSTR, 1 , POS(OLDTXT,NEWSTR)-1) ||,
TMPTXT || SUBSTR(NEWSTR, POS(OLDTXT,NEWSTR) + LENGTH(OLDTXT))
END
DO WHILE POS(TMPTXT,NEWSTR) > 0
NEWSTR = SUBSTR(NEWSTR, 1 , POS(TMPTXT,NEWSTR)-1) ||,
NEWTXT || SUBSTR(NEWSTR, POS(TMPTXT,NEWSTR) + LENGTH(TMPTXT))
END
RETURN NEWSTR

Related Posts




blog comments powered by Disqus

There's 5 Comments So Far

  •   _PeUR
    March 22nd, 2011 at 8:34 pm

    Thank you for that.

    At the 16th line, must be NEWTX and not NEW

  •   Karthik
    March 30th, 2011 at 1:21 pm

    Thanks PeUR, Corrected!

  •   JIten
    January 30th, 2013 at 10:35 am

    scenario:
    str = ‘ my new ride ‘
    old text = ‘new’
    new text = ‘new first’

    code will enter in an endless loop…

    share yer thougts!

  •   Karthik
    January 31st, 2013 at 8:10 am

    oh.. yes, if the old text is a sub string of new text, there will be an infinite loop.. I have now updated the code, such that it will work even for the case you mentioned

  •   JIten
    February 1st, 2013 at 12:00 pm

    Thanks!
    Appreciate your work!!!

Share your thoughts, leave a comment!