8

Here is a sample of code I am working on:

\documentclass[10pt]{report}

\usepackage{xstring}
\usepackage{ifthen}
\begin{document}

\StrLen{123456}\\                                    %Prints 6      
\ifthenelse{\equal{6}{6}}{TRUE}{FALSE}\\              %Prints True
%\ifthenelse{\equal{\StrLen{123456}}{6}}{TRUE}{FALSE} %Want to print true


\end{document}

I am trying to nest a command inside another command. In this case the \StrLen command inside the \ifthenelse command. Is there a way to get around the problem I am running into?

9

The problem with your attempt and the solution are explained in the xstring documentation:

The macros of this package are not purely expandable, i.e. they cannot be put in the argument of an \edef. Nestling macros is not possible neither.

For this reason, all the macros returning a result (i.e. all excepted the tests) have an optional argument in last position. The syntax is [ name ], where name is the name of the control sequence that will receive the result of the macro: the assignment is made with an \edef which make the result of the macro name purely expandable. Of course, if an optional argument is present, the macro does not display anything.

Thus, the solution is to use the optional argument of \StrLen to store the length in a command and then use this command inside ifthenelse:

\documentclass{report}
\usepackage{xstring}
\usepackage{ifthen}

\newcommand\CompLen[1]{%
  \StrLen{#1}[\MyStrLen]% we find the length of the string and store it in \MyStrLen
  \ifthenelse{\equal{\MyStrLen}{6}}% we compare the length of the string with 6
        {TRUE}{FALSE}}

\begin{document}

\CompLen{123456}
\CompLen{123}

\end{document}
-1

Since you're testing numbers, you want

\ifthenelse{\StrLen{123456} = 6}{TRUE}{FALSE}
  • 2
    This doesn't work because \StrLen isn't fully expandable, i.e. requires assignments. – Martin Scharrer Apr 9 '11 at 22:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy