The "smart string" literal is a more powerful version of the standard string literal.
It has three advantages:
Examples:
String Interpolation
Smart strings can hold zero or more placeholders with code. The placeholders can be easily formatted.
A placeholder starts with $[optional formatter]{ and ends with }:
You can put any code you like inside the placeholders.
This is a compile time feature. You cannot load the strings from a file for example.
Number Formatter
The number formatter allows you to set the minimum number of integers and the maximum number of fractions digits. It is similar to NumberFormat keyword.
The number formatter structure: MinIntegers.MaxFractions. MaxFractions component is optional.
Examples:
Other Formatters
Note that the formatters are case insensitive.
Date - Equivalent to DateTime.Date:
Time - Equivalent to DateTime.Time:
DateTime - Equivalent to DateTime.Date & " " & DateTime.Time:
XML - Escapes the five XML entities (", ', <, >, &):
This is also useful for html content.
It has three advantages:
- Supports multi-line strings.
- No need to escape quotes.
- Supports string interpolation.
Examples:
B4X:
Dim s As String = $"Hello world"$
Dim query As String = $"
SELECT value_id FROM table3
WHERE rowid >= random()%(SELECT max(rowid)FROM table3)
AND second_value ISNOTNULL
LIMIT 1"$
Log($"No need to escape "quotes"! "$)
String Interpolation
Smart strings can hold zero or more placeholders with code. The placeholders can be easily formatted.
A placeholder starts with $[optional formatter]{ and ends with }:
B4X:
Log($"5 * 3 = ${5 * 3}"$) '5 * 3 = 15
B4X:
Dim x = 1, y = 2, z = 4 As Int
Log($"x = ${x}, y = ${y}, z = ${Sin(z)}"$) 'x = 1, y = 2, z = -0.7568024953079282
This is a compile time feature. You cannot load the strings from a file for example.
Number Formatter
The number formatter allows you to set the minimum number of integers and the maximum number of fractions digits. It is similar to NumberFormat keyword.
The number formatter structure: MinIntegers.MaxFractions. MaxFractions component is optional.
Examples:
B4X:
Dim h = 2, m = 15, s = 7 As Int
Log($"Remaining time $2{h}:$2{m}:$2{s}"$) 'Remaining time 02:15:07
Log($"10 / 7 = $0.3{10 / 7}"$) '10 / 7 = 1.429
Log($"$1.2{"The value is not a number!"}"$) 'NaN
Other Formatters
Note that the formatters are case insensitive.
Date - Equivalent to DateTime.Date:
B4X:
Log($"Current date is $date{DateTime.Now}"$) 'Current date is 02/02/2015
Time - Equivalent to DateTime.Time:
B4X:
Log($"Current time is $time{DateTime.Now}"$) 'Current time is 11:17:45
DateTime - Equivalent to DateTime.Date & " " & DateTime.Time:
B4X:
Log($"Current time is $DateTime{DateTime.Now}"$) 'Current time is 02/02/2015 11:18:36
XML - Escapes the five XML entities (", ', <, >, &):
B4X:
Dim UserString As String = $"will it break your parser ><'"&?"$
Log($"User input is: $xml{UserString}"$)
'User input is: will it break your parser ><'"&?
Last edited: