
我需要創建一個函數來轉換字串,例如:
Hello\textbackslash{}Bye
進入這個:
Hello \\ Bye
我嘗試使用StrSubstitute
(從xstring
包中)但沒有成功。我已經嘗試過以下幾件事:
\newcommand{\TRANSFORM}[1]{\StrSubstitute{#1}{\textbackslash{}}{ \noexpand\\ }}
\TRANSFORM{Hello\textbackslash{}Bye}
答案1
你可以暫時重新定義 的意義\textbackslash
,讓它\\
:
\documentclass{article}
\newcommand{\TRANSFORM}[1]{{\let\textbackslash\\#1}}
\setlength{\parindent}{0pt}% Just for this example
\begin{document}
Hello\textbackslash{}Bye
\TRANSFORM{Hello\textbackslash{}Bye}
\end{document}
答案2
您需要使用\noexpandarg
的模式xstring
,因此它不會嘗試擴展其參數:
\documentclass{article}
\usepackage{xstring}
%\noexpandarg % set \noexpandarg globally
\newcommand{\TRANSFORM}[1]{%
\saveexpandmode\noexpandarg % set \noexpandarg locally
\StrSubstitute{#1}{\textbackslash{}}{\\}%
\restoreexpandmode % restore the previous mode
}
\begin{document}
\TRANSFORM{Hello\textbackslash{}Bye}
\end{document}
根據您的使用情況xstring
,您也可以進行\noexpandarg
全域設定(透過註解/取消註解相關行)。
當然,在這種情況下,重新定義一個巨集會更好:
\newcommand\TRANSFORM[1]{{% open a group
\renewcommand{\textbackslash}[1]{\\}%
#1%
}}
為什麼\renewcommand
又不呢\let
?因為這個重新定義也吞噬了{}
。