[Tex/LaTex] Extract first letter of each word, also after a special character like a dash

acronymslatex3macros

This question based on this answer.

Found letter missing when it occurs next to dash, as per the below MWE:

\documentclass{article}
\usepackage{readarray}
\usepackage{ifthen}
\newcounter{index}\setcounter{index}{0}
\def\firstletters#1{%
  \getargsC{#1}%
  \whiledo{\theindex<\narg}{%
    \stepcounter{index}%
    \edef\nextword{\csname arg\romannumeral\theindex\endcsname}%
    \expandafter\getfirst\nextword\relax%
  }%
}
\def\getfirst#1#2\relax{#1}
\begin{document}
\firstletters{This is a test of the Emergency Broadcast System. This-Test. for sample. This T.}
\end{document}

Output

Best Answer

The datatool package provides \DTLinitials. For example:

\documentclass{article}

\usepackage{datatool-base}

\begin{document}

\DTLinitials{This is a test of the Emergency Broadcast System.
This-Test. for sample. This T.}

\end{document}

T.i.a.t.o.t.E.B.S.T.-T.f.s.T.T.

This automatically inserts a period after each initial, but that can be prevented by redefining \DTLafterinitials, \DTLbetweeninitials and \DTLafterinitialbeforehyphen to do nothing.

\documentclass{article}

\usepackage{datatool-base}

\renewcommand*{\DTLbetweeninitials}{}
\renewcommand*{\DTLafterinitials}{}
\renewcommand*{\DTLafterinitialbeforehyphen}{}

\begin{document}

\DTLinitials{This is a test of the Emergency Broadcast System.
This-Test. for sample. This T.}

\end{document}

TiatotEBST-TfsTT

If you need the initials in an expandable context, you first need to use \DTLstoreinitials, which will save the initials in the command provided in the second argument:

\DTLstoreinitials{This is a test of the Emergency Broadcast System.
This-Test. for sample. This T.}{\initials}

\initials

Edit: if you also want to remove the hyphen from the initials, just redefine \DTLinitialhyphen to do nothing as well:

\renewcommand*{\DTLinitialhyphen}{}

Edit2: Note that \DTLinitials is designed primarily for names (its original purpose was for use with the abbreviated bibliography style provided by databib) so it assumes its argument is a series of letters separated by spaces or hyphens. Additionally from the manual:

Be careful if the initial letter has an accent. The accented letter needs to be placed in a group, if you want the initial to also have an accent, otherwise the accent command will be ignored.

So, as per your comment below:

\DTLinitials{{\"{O}}zg\"{u}r}

Or use XeLaTeX or LuaLaTeX with UTF-8 characters. This is similar to the limitations on \makefirstuc (from mfirstuc)

Also from the datatool manual:

In fact, any command which appears at the start of the name that is not enclosed in a group will be ignored.

This means that, say

\DTLinitials{\MakeUppercase{m}ary ann}

will produce m.a. not M.a.