Find the longest word in a string

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".

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

\documentclass{article}
\usepackage{stringstrings}
\usepackage{listofitems}
\makeatletter
\newcommand\longest[1]{
\setsepchar{ }
\xdef\sentence{#1}
\def\longestword{}
\def\longestwordcount{0}
\newcounter{@wordlength}
\foreachitem\word\in\wordlist{
\@getstringlength{\word}{@wordlength}
\ifnum\the@wordlength>\longestwordcount\relax%
\xdef\longestword{\word}
\xdef\longestwordcount{\the@wordlength}
\fi
}
}
\makeatother
\begin{document}
% Count number of strings
\longest{the lazy dog stackexchange}
\obeyspaces The longest word was \longestword and had \longestwordcount characters
\end{document}

• 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:

\documentclass{article}
\usepackage{xparse}
\usepackage{expl3}
\ExplSyntaxOn
\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} }
}
\ExplSyntaxOff
\begin{document}
\longestword{I am an annoying stackexchange user}
\end{document}


(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.)