String formatting made easy for .NET

Everyone who is used to .NET framework knows string.format. It's quite powerful in formatting all kind of objects and also has some aligning features. I wrote my own simple string formatting class, with a bit different alignment possibilities, with text macro support and missing macro callbacks.

The reason for writing this formatter was to easily format text for text-based customer displays, which in fact is not a very challenging task, and to format text for text-based receipt printers.

Formatting syntax

The syntax is similar to the syntax used by string.Format. Each format-packet is enclosed by curly brackets and contains colon seperated fields. the fields are as follows:

  1. Macro-name, text or index:Macro-names are enclosed by square brackets and text is enclosed by double quotes
  2. Padding specifier:
    • L - Left-aligned not filled, no padding. Default if no padding is specified. Text does not get truncated.
    • LF - Left-aligned and fill. Text gets left aligned and missing characters are filled up with the padding character. The text
      gets truncated if it is longer than the specified padding length
    • M - Centered output. The text gets centered by the specified padding length and gets truncated id the text is longer than
      the padding length.
    • R - Right-aligned output. The text gets right aligned by the specified padding length and is truncated if the text is longer
      than the specified padding length.
  3. Padding Width: Specifies the padding width as used by the corresponding padding specifier
  4. Padding character: Specifies the padding character used for padding. Use only a single character, no quoting.


The following code f.Format("{0:LF:10:-}{1:R:10:*}", "Hello", "World") produces
This shows the left-aligned and right-aligned text output. More padding samples can be found in the source code.

The above code samples uses the indizes (as also used by string.format) to reference the string to format, but the simple formatter also supports text macros. Once a macro is registered it can be used as shown and produces the expected output:

f.DefineTextMacro("hello", "HELLO");

But also if a used macro is not registered you can register to receive an event once an unregistered macro is used as shown below:

f.OnGetParameter += OnGetParameter;

private static string OnGetParameter (string parameterName){
  //Return some parameter values

For each instance of [universe] the OnGetParameter event is raised and the code may return different values at different times.

Source code

Check out the code at git clone git:// Run the samples to see how it works, the formatter is located Deveck.Utils/StringUtils/StringFormatter.cs