This question already has an answer here:

I'm an aspiring LaTeX user and have so far managed the first steps and created my first few documents. Coming from a programming background I've been wondering how you could use \newcommand to create a command that formats numbers or strings in a hard-coded way.

For example, let's say I have the string AB1234567890. Now what I'd like to do is create a command, that used like this


should create the output

AB12 3456 7890

I realize something like that can be done with \,


but I would like to define a fixed "layout" in the command to make sure that every string gets formated the same way as I use that command with each string later.

In a programming language I could split strings and such but I'm unaware how to solve that with LaTeX.

marked as duplicate by egreg, Peter Grill, Werner, Martin Schröder, ChrisS Feb 19 '14 at 23:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Are those strings always twelve character long? – egreg Feb 19 '14 at 22:43
  • In your example, do you want a space every four character from the left or from the right? Generally, you need to write a macro for every different format. It is usually possible if the desired format is specified precisely enough, but there are so many different possibilities that little can be said in general. – Dan Feb 19 '14 at 22:47
  • Yes, the strings are always the same length. The counting should begin from the left, however the space is not necessarily always after 4 chars. – LumenAlbum Feb 22 '14 at 23:46

You could use the xstring package:

enter image description here


  • An enhanced version is available at putting spaces within text block.
  • There is a limit in this code of 400 characters, so please adjust the ending value of the \foreach as desired.
  • By default the split is done from the left. If you desire the split to be from the right, you need to pass in the first optional parameter with something other than L.



        \foreach \x in {1,...,100} {%
        \multicolumn{1}{c}{Left} & \multicolumn{1}{c}{Right} \\
    \applyformat{AB1234567890}   & \applyformat[R]{AB1234567890}\\
    \applyformat{AB123456789}    & \applyformat[R]{AB123456789}\\
    \applyformat{AB12345678}     & \applyformat[R]{AB12345678}\\
    \applyformat{AB1234567}      & \applyformat[R]{AB1234567}\\
    \applyformat{AB12}           & \applyformat[R]{AB12}\\
    \applyformat{AB}             & \applyformat[R]{AB}\\
    \applyformat{A}              & \applyformat[R]{A}\\
  • This looks like it's exactly what I need. Thank you! I'm surprised that this requires such an elaborate solution In LaTeX, though. There's a lot I need to learn – LumenAlbum Feb 22 '14 at 23:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.