I want to extract the last word of a sentence stored in a variable, e.g. \thevariable. Here is the minimal example.
\documentclass{article}
% Function to extract the last word of a sentence
\protected\def\TheLastWord#1{\xreverseit{}#1 \relax}
\def\xreverseit#1#2 #3{%
\ifx\relax#3%
#2%
\expandafter\xthree
\fi
\xreverseit{#1 #2}#3}
\def\xthree#1#2#3{}
\newcommand\thevariable{The example sentence} % Store the sentence in a variable
\begin{document}
\TheLastWord{The example sentence} % Will print the last word 'sentence' -> CORRECT!
\TheLastWord{\thevariable} % Will just print the whole sentence: 'The example sentence' -> WRONG!
\end{document}
The code and the function\TheLastWord were picked up and modified from David Carlisle's excellent work as shown here.
As you can see with the minimal example, it works for text input (\TheLastWord{The example sentence}) but is failed when the input is a variable (\TheLastWord{\thevariable}) storing the same sentence.
What is the reason for this failure? How to modify the code to make it work with the variable input?

\expandafter\TheLastWord\expandafter{\thevariable}– egreg Mar 31 '15 at 16:39