Version: Unity 6.7 Alpha (6000.7)
Language : English
Plural formatter
Template formatter

Sub String formatter

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.

Anatomy of the substr formatter syntax.
Anatomy of the substr formatter syntax.

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:

  • ReturnEmptyString returns an empty string. This is the default.
  • ReturnStartIndexToEndOfString returns the rest of the string from the start index.
  • ThrowException throws a 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"

Additional resources

Plural formatter
Template formatter