See also std.conv.
(1) immutability
|
def main():
s = "hello"
print(s[0]) # 'h'
s[0] = "H" # Error!
|
import std.stdio;
void main()
{
string s = "hello";
writeln(s[0]); // 'h'
s[0] = 'H'; // Error!
}
|
String length
(2) length of a string
|
def main():
s = "Éva"
print(len(s)) # 3, number of chars
|
import std.stdio;
import std.conv; // to()
void main()
{
string s = "Éva"; // stored in UTF-8
writeln(s.length); // 4, number of bytes
writeln(s.to!dstring.length); // 3
}
|
dstring
uses UTF-32 encoding, thus every character occupies 4 bytes. But in 4 bytes every Unicode character can be stored.
String concatenation
(3) concatenation
|
def main():
s = "aa"
t = s
print(s) # aa
s += "bb"
print(s) # aabb
print(t) # aa
|
import std.stdio;
void main()
{
string s = "aa";
string t = s;
writeln(s); // aa
s ~= "bb";
writeln(s); // aabb
writeln(t); // aa
}
|
D uses the '~'
sign for concatenation.