Is there a simple way to get the longest word in a string? I would know how to program it in some other languages, but I'm afraid my latex kung-fu is not up to par...

To make it clear, I want to make a function \longword{} that (for example) on input {I am an annoying stackexchange user} will return "stackexchange".

  • 1
    Can you give an example and some motivation? – egreg Aug 31 '18 at 9:43

I don't know about simple, but I made this for you:

  \setsepchar{ }
% Count number of strings
\longest{the lazy dog stackexchange}
\obeyspaces The longest word was \longestword and had \longestwordcount characters
  • 1
    Thank you! To make it work properly I had to change \def\longestword{\word} to \xdef\longestword{\word}. Otherwise it always gives the last word as \longestword (which in your example makes no difference, probably why you didn't catch the bug) – Alexbib Sep 1 '18 at 5:24
  • @Alexbib true! Because the \word macro keeps changing and the \xdef expands it fully. Fixed in the answer now :) – Andreas Storvik Strauman Sep 1 '18 at 8:04

Using expl3:

\NewDocumentCommand { \longestword } { m }
  { \alexbib_longest_word:n {#1} }
\cs_new:Npx \alexbib_longest_word:n #1
   \exp_not:N \__alexbib_longest_word:nnw
     { 0 } { } #1 ~
     \exp_not:N \q_recursion_tail \c_space_tl \exp_not:N\q_recursion_stop
\cs_new:Npn \__alexbib_longest_word:nnw #1#2#3 ~
    \quark_if_recursion_tail_stop_do:nn {#3} {#2}
    \int_compare:nNnTF { \tl_count:n {#3} } > { #1 }
        \exp_args:Nf \__alexbib_longest_word:nnw
          { \int_eval:n { \tl_count:n {#3} } } {#3}
      { \__alexbib_longest_word:nnw {#1} {#2} }
\longestword{I am an annoying stackexchange user}

(I've assumed that we are counting 'length' on a token basis: I'm not sure if for example \'{e} counts as one or two letters.)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.