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

5 thoughts on “REXX – STRREPLACE : Replace part of a string with new string”

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

    code will enter in an endless loop…

    share yer thougts!

  2. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.