Output part of a string inside a Smart String.
The Sub String formatter returns a portion of a string value, selected by a start index and an optional length. If the value isn’t a string, it’s first converted to one with ToString. Apply it explicitly with the name substr.
flowchart TD
full["{value:substr(start,length)}"]
full --> p1["value"]
full --> p2["substr"]
full --> p3["start"]
full --> p4["length"]
p1 --> d1["Any value"]
p2 --> d2["Formatter name: substr"]
p3 --> d3["Start index"]
p4 --> d4["Length (optional)"]
classDef code fill:#F5F5F5,stroke:#BDBDBD,color:#111;
classDef orange fill:none,stroke:none,color:#F37021;
classDef green fill:none,stroke:none,color:#67BC6B;
classDef pink fill:none,stroke:none,color:#EB417A;
class full code;
class p1,d1 orange;
class p2,d2 green;
class p3,d3 pink;
class p4,d4 pink;
linkStyle default stroke:#2196F3,stroke-width:1.5px;
The first argument of the substr formatter is the start index. The optional second argument is the length. A negative start index counts back from the end of the string, and a negative length counts back from the end.
The start index and length use the split character to separate them. Valid split characters are , (comma, the default), | (pipe), and ~ (tilde). Configure it with SubStringFormatter.SplitChar.
When a null value is reached, the formatter writes the Null Display String, which defaults to (null). Configure it with SubStringFormatter.NullDisplayString. If a nested format is supplied instead, the nested format receives the null and is responsible for handling it.
A supplied format must contain a nested placeholder, otherwise the formatter throws a FormattingException.
SubStringFormatter.OutOfRangeBehavior controls what happens when the start index or length goes past the end of the string. The available options are:
FormattingException.| Smart String | Argument | Result |
|---|---|---|
{0:substr(5)} |
"Long John" |
John |
{0:substr(0,3)} |
"New York" |
New |
{0:substr(-4)} |
"Long John" |
John |
{0:substr(-4,2)} |
"Long John" |
Jo |
{0:substr(-4,-1)} |
"Long John" |
Joh |
Hello {name:substr(1)} {surname} |
name = "Lara", surname = "Croft"
|
Hello ara Croft |
You can pass the result to a nested placeholder to keep formatting it:
Smart.Format("{0:substr(0,2):{ToLower}}", "ABC"); // "ab"