Using the expl3
package, the splitting can be quite easily achieved by using the \seq_set_split:Nnn
function. The first parameter of this function is the target sequence where the individual elements are stored, the second parameter is the delimiter to split at (we have to use ~
instead of a space character here, because in expl3
syntax mode bare spaces are ignored), and the last parameter is the text to be split.
After splitting we set \FirstName
and \LastName
empty, and then fill them again, depending on how many elements are present after splitting the input: for one set only the first name, for two set first and last name, for three the former two are treated as the first name and the latter one is treated as the last name.
If you are not familiar with the expl3
syntax, the code may be a bit hard to read, but the implementation is actually quite straight-forward.
\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\newcommand\FullName[1]{%
\seq_set_split:Nnn \l_tmpa_seq { ~ } { #1 }
\cs_gset:Npx \FirstName { }
\cs_gset:Npx \LastName { }
\int_case:nn { \seq_count:N \l_tmpa_seq } {
{ 1 } {
\cs_gset:Npx \FirstName { \seq_item:Nn \l_tmpa_seq { 1 } }
}
{ 2 } {
\cs_gset:Npx \FirstName { \seq_item:Nn \l_tmpa_seq { 1 } }
\cs_gset:Npx \LastName { \seq_item:Nn \l_tmpa_seq { 2 } }
}
{ 3 } {
\cs_gset:Npx \FirstName { \seq_item:Nn \l_tmpa_seq { 1 } ~
\seq_item:Nn \l_tmpa_seq { 2 } }
\cs_gset:Npx \LastName { \seq_item:Nn \l_tmpa_seq { 3 } }
}
}
}
\ExplSyntaxOff
\begin{document}
\FullName{}
First: ``\FirstName'', Last: ``\LastName''\par
\FullName{John}
First: ``\FirstName'', Last: ``\LastName''\par
\FullName{John Citizen}
First: ``\FirstName'', Last: ``\LastName''\par
\FullName{John K. Citizen}
First: ``\FirstName'', Last: ``\LastName''\par
\end{document}
outputs