[Tex/LaTex] How to remove the first and last letter of a string

text manipulationxstring

My example.

Need from the string "$${{15}\over{4}}$$" get the string "${{15}\over{4}}$".

\documentclass[14pt]{extarticle}
\usepackage{xstring}
\usepackage{amsmath}

\def\f(#1){(#1)^2-5*(#1)+6}


\begin{document} 

\section{Problem}
Evaluate $f(x)=\f(x)$ for $x=\frac 1 2$.

\section{Solution}
\immediate\write18{cas "x: 1/2\string$ tex(\f(x))\string$"}
\def\SX{\input{solution}}%This file has a string "$${{15}\over{4}}$$"

\StrGobbleLeft{\SX}{1}[\SX]%It produces an error
\StrGobbleRight{\SX}{1}[\SX]%It produces an error
$f(x)=$\SX

\end{document}

Thanks in advance.

Best Answer

With your code, \SX expands to \input{solution}, not to the contents of the file.

With catchfile it should work; you can even ignore the $ signs:

\documentclass[14pt]{extarticle}
\usepackage{catchfile}
\usepackage{amsmath}

\def\f(#1){(#1)^2-5*(#1)+6}


\begin{document}

\section{Problem}
Evaluate $f(x)=\f(x)$ for $x=\frac 1 2$.

\section{Solution}
\immediate\write18{cas "x: 1/2\string$ tex(\f(x))\string$"}

%% Read the solution file, ignoring $
\CatchFileDef\SX{solution}{\catcode`\$=9 }

$f(x)=\SX$

\end{document}

enter image description here

If you want fuller control and use xstring, then you have to use the \expandarg mode, not the default \fullexpandarg, because \over is not the (unexpandable) primitive any more when amsmath is loaded.

% catch the contents of solution.tex, removing the trailing space
\CatchFileDef\SX{solution}{\endlinechar=-1 }
\expandarg
\StrGobbleLeft{\SX}{2}[\SX]
\StrGobbleRight{\SX}{2}[\SX]

I'd remove all the $ signs, because $f(x)=$$$ is incorrect as far as spacing is concerned.