Everyone who is used to .NET Framework knows string.format
. It's quite powerful in formatting all kinds of objects and also has some aligning features. I wrote my own simple string
formatting class, with slightly 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 separated fields. The fields are as follows:
- Macro-name, text or index: Macro-names are enclosed by square brackets and text is enclosed by double quotes
- 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.
- Padding Width: Specifies the padding width as used by the corresponding padding specifier
- Padding character: Specifies the padding character used for padding. Use only a single character, no quoting.
Samples
The following code:
f.Format("{0:LF:10:-}{1:R:10:*}", "Hello", "World")
produces:
Hello-----*****World
This shows the left-aligned and right-aligned text output. More padding samples can be found in the source code.
The above code samples use the indices (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");
f.Format("{[hello]:LF:10:-}");
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;
Console.Write(f.Format("{[universe]}"));
private static string OnGetParameter (string parameterName){
}
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://github.com/deveck/Deveck.Utils.git.
Run the samples to see how it works.
The formatter is located at Deveck.Utils/StringUtils/StringFormatter.cs.
CodeProject
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.