Performing String Replacements and Substitutions

QUESTION: I have a string with a string substitution marker in it. I want to replace the marker with a substring. What is the most efficient way to do that?

For example, if have these strings:

   IDL> substring = 'Coyote'
   IDL> myString = 'The %1 is my favorite animal.'

I want an efficient operation that will replace “%1” with “Coyote” to give me this string:

   newString = 'The Coyote is my favorite animal.'

ANSWER: The easiest thing to do is use a combination of the StrSplit and StrJoin commands to perform the substitution for you. Using regular expressions with StrSplit is an extremely powerful way to search for and separate string markers.

For example, if we define the regular expression we are searching for like this (notice we have to escape the % sign with a backslash character, since the % sign has a particular meaning in a regular expression):

   IDL> expression = '\%1'
Then, we can perform the string substitution like this:

    IDL> Print, StrJoin( StrSplit(myString, expression, /Regex, /Extract, $
           /Preserve_Null), substring)
           The Coyote is my favorite animal.

If you are serious about string substitution, go get Mike Galloy's STR_REPLACE command and the White Paper Mike wrote on regular string expressions. That's the right way to do something like this.

[Return to IDL Programming Tips]