# Generating a string (for filename) without space

My situation is this. I have a string in some macro definition which is to be used as a file name. Before I create the file, I want to remove all the spaces from that name. I tried something like this following.

\documentclass{article}

\usepackage{xstring}

\def\namewithspaces{A Name With Space}

\newtoks\tempstring
\def\createfilewithoutspaceinname#1{\tempstring=\expandafter{\StrDel{#1}{ }.lst}
\typeout{\the\tempstring}
\newwrite\fl
\openout\fl=\the\tempstring}

\begin{document}

\createfilewithoutspaceinname{\namewithspaces}

\end{document}


I expected the file name to be something like, ANameWithSpace.lst, but in reality this is not happening.

As can be seen from the added \typeout command, the value of \tempstring is,

\let \@xs@assign \@xs@expand@and@assign \@xs@StrSubstitute@ {\namewithspaces }{ }{}.lst


Looks like I am missing something of the expansion.

• I don't think that \StrDel is expandable at all – user31729 Aug 23 '16 at 11:23

In my opinion, the \tempstring should be a macro which is used as the last optional argument of \StrDel and this macro should be fed to \openout\tl.

I also recommend not to use a \newwrite each time \createfilenamewithspaceinname is applied (unless the file is closed etc. or in a group)

\documentclass{article}

\usepackage{xstring}

\def\namewithspaces{A Name With Space}

\newwrite\fl%

\def\tempstring{}
\def\createfilewithoutspaceinname#1{%
\expandarg\StrDel{#1.lst}{ }[\tempstring]
\typeout{tempstring is \tempstring}
\immediate\openout\fl=\tempstring
}

\begin{document}

\createfilewithoutspaceinname{\namewithspaces}

\immediate\write\fl{\string Hello World}

\immediate\closeout\fl

\end{document}

• This solutions suits me better because actually, I am going to use \StrSubstitute to remove all special characters from the file name. And, yes, I am do closing the file before creating a new one. Thanks for reminding me. – Masroor Aug 23 '16 at 11:57
• @Masroor: You're welcome. Perhaps using expl3 features it might be even easier to get what you want, but that's another approach to learn. – user31729 Aug 23 '16 at 12:03

xstring commands mostly do not work by expansion. The latex format includes an expandable command to remove spaces.

\documentclass{article}

\def\namewithspaces{A Name With Space}

\makeatletter
\def\createfilewithoutspaceinname#1{%
\typeout{\expandafter\zap@space#1 \@empty}}
\makeatother

\begin{document}

\createfilewithoutspaceinname{\namewithspaces}

\end{document}


causes a message of

ANameWithSpace


on the console