See also std.conv.
With ASCII text
(1) string slicing ASCII text
|
def main():
# 1
# 01234567890
s = "programming"
print(s[0:4]) # prog
print(s[4:7]) # ram
print(s[8:]) # ing
print(s[-3:]) # ing
print(s[-1]) # g
|
import std.stdio;
void main()
{
// 1
// 01234567890
string s = "programming";
writeln(s[0 .. 4]); // prog
writeln(s[4 .. 7]); // ram
writeln(s[8 .. $]); // ing
writeln(s[$ - 3 .. $]); // ing
writeln(s[$ - 1]); // g
}
|
|
$ means the length of the string, i.e. s.length
|
With Unicode text
(2) string slicing Unicode text
|
def main():
# 01234
s = "árvíz"
print(s[0:2]) # ár
|
import std.stdio;
import std.conv;
void main()
{
// 01234
string s = "árvíz";
writeln(s[0 .. 2]); // á !!! first two bytes
dstring t = s.to!dstring;
writeln(t[0 .. 2]); // ár , first two characters
}
|
string
is UTF-8 encoded, where a character can be represented by 1, 2, 3 or 4 bytes. s[0 .. 2]
means the first two bytes. The character "á" is stored in 2 bytes in UTF-8 (b'\xc3\xa1'
).