Apply an operation on every word/character

macros

There are some related questions:

Apply a macro to every word

Iterate over space-separated list

How to repeat over all characters in a string?

But every post I found asked for something specific and it was really hard to understand which is the part actually needed for applying a certain operation on all characters/words. Let's say we have a \newcommand\command1[1]{do something} and we want to apply this on every character and \newcommand\command2[1]{do something} which we want to apply on every word. How would we go about it?

Best Answer

Use expl3: both commands have a second argument that's a template for what to do with the characters or the words.

In the last case, we need ##1 for the nested call.

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\applytoeverychar}{mm}
 {
  \group_begin:
  \tl_set:Nn \l_tmpa_tl { #1 }
  \tl_replace_all:Nnn \l_tmpa_tl { ~ } { \c_space_tl }
  \cs_set_protected:Nn \__masum_apply:n { #2 }
  \tl_map_function:NN \l_tmpa_tl \__masum_apply:n
  \group_end:
 }

\NewDocumentCommand{\applytoeveryword}{mm}
 {
  \group_begin:
  \seq_set_split:Nnn \l_tmpa_seq { ~ } { #1 }
  \cs_set_protected:Nn \__masum_apply:n { #2 }
  \seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq { \__masum_apply:n { ##1 } }
  \seq_use:Nn \l_tmpb_seq { ~ }
  \group_end:
 }

\cs_new:Nn \__masum_apply:n {} % initialize

\ExplSyntaxOff

\begin{document}

\applytoeverychar{do something}{\textlangle #1\textrangle}

\applytoeveryword{do something}{\textlangle #1\textrangle}

\applytoeveryword{do something}{\textbar\applytoeverychar{#1}{\textlangle##1\textrangle}\textbar}

\end{document}

enter image description here