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
Advertisement

6 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

  3. Very nice. Big thanks. I used it to rplace all occurances I have in a string where there are two commas side by side with comma X comma. I could then do a WORDS to get a count of words in the string. That helped in putting all the words into a compound variable when the total of words are unpredictable.

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 )

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.