[Tex/LaTex] strip last character from parameter if it is ‘s’

macrosstrings

I have a semantic annotation \monster to annotate mentions of monsters so that they are indexed:

\newcommand{\indexMonster}[1]{\index{#1}}
\newcommand{\monster}[1]{#1\indexMonster{#1}}

Now, most of the monsters mentions are in plural but some are not. I would like the index entries to be in singular. So I am looking for a way to strip the last character of the \monster argument if it is 's'.

Best Answer

This solution uses xstring. Since there are some terrible monsters named albatross which are intesly feared, and you of course will be writing a lot about, I have also made a warning system for when the names of monsters have been changed. You can of course drop this if you feel like. If you want to override the test for monsters ending in s, simply add braces around your monster, like in the example below.

Output enter image description here

Code

\documentclass[11pt,draft]{article}
\usepackage{xstring}
\usepackage{ifdraft}
\newcommand{\indexMonster}[1]{\index{#1}}
\newcommand{\monster}[1]{%
    \IfEndWith{#1}{s}{%
    % Do nothing if ends with s.
    \StrGobbleRight{#1}{1}[\result]%
    \result\indexMonster{\result}%
    % Issue a warning on changed monsters
    \ifdraft{%
    \marginpar{Monster \textbf{#1} was changed to \result.}%
    }{}%%
    }{%
    #1\indexMonster{#1}}%
    }
\begin{document}
\monster{Dogs} \monster{Dog} \monster{albatross} \monster{{albatross}}
\end{document}

Second solution

Here is my attempt at this with expl3. I just did the text-replacement, not the indexing, but that should be trivial.

\documentclass[11pt]{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\monster}{m}
 {
  \l_wilx_monster:n { #1 }
 }

\cs_new_protected:Nn \l_wilx_monster:n
 {
    % Check if last character is "s"
    \str_if_eq_x:nnTF { \str_item:nn {#1} {-1} } {s} 
        % True: print string expect for last string (in other words, remove s)
        {\str_range:nnn {#1} {1} {-2}} %
        % False: Print string as usual
        {#1}
 }
\ExplSyntaxOff

\begin{document}
\monster{dogs}
\end{document}
Related Question