找到字符串中最长的单词

找到字符串中最长的单词

有没有简单的方法可以获取字符串中最长的单词?我知道如何用其他语言来编程,但我担心我的乳胶功夫不够好……

为了清楚起见,我想创建一个函数 \longword{},(例如)当输入 {I am an annoying stackexchange user} 时将返回“stackexchange”。

答案1

我不知道简单与否,但我为你做了这个:

\documentclass{article}
\usepackage{stringstrings}
\usepackage{listofitems}
\makeatletter
\newcommand\longest[1]{
  \setsepchar{ }
  \xdef\sentence{#1}
  \readlist\wordlist\sentence
  \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}

答案2

使用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}

(我假设我们是根据标记来计算“长度”:我不确定例如是否\'{e}算作一个还是两个字母。)

相关内容