27

I've got a string like this: aXYbXYc, and need to replace the XY substring with a right arrow: a $\to$ b $\to$ c.

Is there any function (also provided by external packages) to help me do that?

peoro
  • 1,299

2 Answers2

29
\documentclass{article}
\usepackage{xstring}
\def\ReplaceStr#1{%
  \IfSubStr{#1}{XY}{%
    \StrSubstitute{#1}{XY}{$\to$}}{#1}}

\begin{document}

\ReplaceStr{aXYbXYc}

\ReplaceStr{abc}

\end{document}
2
\documentclass{article}
\usepackage{listofitems}
\newcommand\substr[3]{%
  \setsepchar{#2}%
  \readlist\parsedinput{#1}%
  \foreachitem\x\in\parsedinput{%
    \ifnum\xcnt=1\else#3\fi\x%
  }%
}
\begin{document}
\substr{aXYbXYc}{XY}{$\to$}
\end{document}

enter image description here

  • I've tried to use your \substr twice but couldn't make it work. Can you tell me what I did wrong? For instance, I added spaces in the starting string and I'd like to remove them in addition to the usual substitution. Here the code: \substr{\substr{a XY b XY c}{ }{}}{XY}{$\to$} (The result I get is: aXYbXYcc) TIA! – Stefano Bragaglia Jan 01 '20 at 22:35
  • @StefanoBragaglia One cannot nest invocations of \substr. But in this case, one need not do so, There is an alternate invocation of \readlist (that is, \readlist*) which strips away spaces that surround the searched-for text (in this case, XY). Thus, changing \readlist to \readlist* in the definition of \substr allows for an invocation of \substr{a XY b XY c}{XY}{$\to$}, which does the desired substitution and removes the spaces. – Steven B. Segletes Jan 02 '20 at 00:05
  • Thank you very much for the explanation! Just to add to the conversation, I was looking for a more general solution: what if I'd like to replace spaces with \quad? My own solution is using \StrSubstitute from xstring but has many limitations (to say the least). The trick they use is to set a variable on the fly: \newcommand{\subst}[1]{\StrSubstitute{#1}{XY}{$\to$}[\tempvar]\StrSubstitute{\tempvar}{ }{\quad}} – Stefano Bragaglia Jan 02 '20 at 12:37
  • @StefanoBragaglia listofitems also can employ nested searches, which allows you to search for more than one thing at a time. Then you would use a nested \foreachitem to handle each level of the nest. – Steven B. Segletes Jan 02 '20 at 13:56
  • listofitems seems to be very powerful! I'll study it in more details! Thanks for pointing out these details! – Stefano Bragaglia Jan 02 '20 at 16:59