Skip to content

SubString _ SubStringFormatter

axunonb edited this page Mar 30, 2022 · 2 revisions

The SubStringFormatter lets you output part of an input string.

Syntax Details

{ string : substr(start,length) : {format-placeholder} }

Value formatter name (arguments) optional :format
string "substr" int start
int length
{placeholder} to format the substring

value: Only strings can be processed. Other objects cause a FormattingException.

arguments: The start position and the lenght of the sub-string.

format-placeholder: A nested Placeholder that lets you format the result of the sub-string operation.

Configuration:

string Name: default is substr
The name to use a named formatter

char SplitChar: default is ','

string NullDisplayString:
The string to display for null values, defaults to string.Empty. It will not be applied, if a format option is provided to the formatter. In this case, the child formatter must handle the null result.

SubStringOutOfRangeBehavior OutOfRangeBehavior:
The behavior when start index and/or length are too big. Defaults to SubStringOutOfRangeBehavior.ReturnEmptyString

Examples

Examples use the following variable:

var person = new {Name = "Long John", City = "New York"};

Simple Substrings

Smart.Format("{Name:substr(5)}", person);
// result: "John"

Smart.Format("{City:substr(0,3)}", person);
// result: "New"

Out-of-range Behavior

The behavior of SubStringFormatter in case start index and/or length is out of range can be controlled by SubStringFormatter.OutOfRangeBehavior:

// SubStringOutOfRangeBehavior.ReturnEmptyString (default behavior):
Smart.Format("{Name:substr(0,999)}", person);
// Outputs: "";

// SubStringOutOfRangeBehavior.ReturnStartIndexToEndOfString:
Smart.Format("{Name:substr(0,999)}", person);
// Outputs: "Long John";

// SubStringOutOfRangeBehavior.ThrowException:
Smart.Format("{Name:substr(0,999)}", person) 
// throws FormattingException

Examples with Format argument

The Format argument must contain nested Placeholder, and may contain literal text.

Convert the substring to lower-case
Smart.Format("{0:substr(0,2):{ToLower}}", "ABC");
//                          |        |
//                          + format +
//                             arg
// Outputs: "ab"
Format the substring chars with the ListFormatter

Format the substring with literal text and placeholder.

smart.Format("{0:substr(0,2):First 2 chars\\: {ToLower.ToCharArray:list:'{}'| and }}", "ABC");
// Outputs: "First 2 chars: 'a' and 'b'"
Clone this wiki locally