TransWikia.com

How do I compare a specific string to strings from a group using a loop?

TeX - LaTeX Asked by user24646 on March 2, 2021

I want to compare members of a group of strings to an specific string. Why is this not working ?

documentclass{beamer}
usepackage{tikz}
begin{document}

foreach n in {x,Enu}{

begin{frame}
frametitle{ test } 
 
newcommandx{Enu} 

ifxxn
        this is $E_{nu}$
else
        this is not $E_{nu}$
fi

end{frame}
}

end{document}

enter image description here

2 Answers

Use defx{Enu} instead newcommad. The newcommand does longdef but foreach from tikz does def only. The comparison of two macros by ifx results false if one is defined by def and second by longdef.

Answered by wipet on March 2, 2021

expl3 features a function called str_case:nn(TF), which is in a way the inverse of what you want, but I guess usable for you. It compares a string to a list of strings. There is also str_if_eq:nnTF to just compare two strings. And we can loop over a comma separated list using clist_map_inline:nn.

documentclass[]{beamer}

% we borrow three functions from expl3
ExplSyntaxOn
cs_new_eq:NN forclist clist_map_inline:nn
cs_new_eq:NN strcaseTF str_case:nnTF
cs_new_eq:NN strifeqTF str_if_eq:nnTF
ExplSyntaxOff

begin{document}
forclist{x,Enu,y}
  {%
    begin{frame}
      frametitle{test}
      strcaseTF{#1}
        {
          {x}   {this is `x'}
          {Enu} {this is $E_{nu}$}
        }
        {. One was matched.}
        {No matches found.}
    end{frame}%
  }

forclist{x,Enu}
  {%
    begin{frame}
      frametitle{test2}
      strifeqTF{#1}{Enu}{this is $E_{nu}$}{this is not $E_{nu}$}%
    end{frame}%
  }
end{document}

If you want to stick to foreach (because it can do more than clist_map_inline:nn with its handy ... syntax), you can use str_case:onTF and str_if_eq:onTF instead, which will expand the x and compare its contents:

documentclass[]{beamer}

usepackage[]{tikz}

% we borrow two functions from expl3
ExplSyntaxOn
cs_new_eq:NN strcaseOTF str_case:onTF
cs_new_eq:NN strifeqOTF str_if_eq:onTF
ExplSyntaxOff

begin{document}
foreachx in {x,Enu,y}
  {%
    begin{frame}
      frametitle{test}
      strcaseOTFx
        {
          {x}   {this is `x'}
          {Enu} {this is $E_{nu}$}
        }
        {. One was matched.}
        {No matches found.}
    end{frame}%
  }

foreachx in {x,Enu}
  {%
    begin{frame}
      frametitle{test2}
      strifeqOTFx{Enu}{this is $E_{nu}$}{this is not $E_{nu}$}%
    end{frame}%
  }
end{document}

Answered by Skillmon on March 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP