[Tex/LaTex] Logical String Length

conditionalsstrings

How do I do a conditional 'if then else' statement, based on length of string being greater than (or less than, or equal) a specified value.

For example, something Like

\def\mystring{XYZ}
\def\mythresh{1}
\ifthenelse{\stringlength{\mystring} > \mythresh}{TRUE}{FALSE}

where \stringlength is 'pseudo' for the relevant command, which I am unsure which is the most widely used.

Does the logical greater than operator apply here, or is there another command?

Best Answer

Use the xstring package:

enter image description here

\documentclass{article}
\usepackage{xstring,xifthen}
\begin{document}
\def\mystring{XYZ}
\StrLen{\mystring}[\mystringlen]

\def\mythresh{1}
\ifthenelse{\mystringlen > \mythresh}{TRUE}{FALSE}
\def\mythresh{3}
\ifthenelse{\mystringlen > \mythresh}{TRUE}{FALSE}

\end{document}

\StrLen{<stuff>}[<name>] stores the length of <stuff> in the control sequence <name>.

The use of xifthen is not really necessary. See How to form “if … or … then” conditionals in TeX? and the related Why is the ifthen package obsolete? for alternatives.


stringstrings provides similar functionality:

\documentclass{article}
\usepackage{stringstrings}
\begin{document}
\def\mystring{XYZ}
\stringlength[q]{\mystring}% Result is stored in \theresult

\def\mythresh{1}
\ifnum\theresult>\mythresh TRUE \else FALSE\fi    
\def\mythresh{3}
\ifnum\theresult>\mythresh TRUE \else FALSE\fi
\end{document}
Related Question