Skip to content
Strings
step 1/5

Reading — step 1 of 5

Learn

~1 min readStrings, Arrays, Templates

D strings are UTF-8 encoded immutable arrays of code units:

string s = "hello";        // immutable(char)[]
char[] m = "hello".dup;     // mutable copy
wstring w = "hello"w;       // UTF-16
dstring d = "hello"d;       // UTF-32

String concatenation: ~. NOT +.

string s = "Hello, " ~ "world!";
string t = "a" ~ "b" ~ "c";    // "abc"

string big;
big ~= "chunk ";    // append in place — mutates the variable's slice

String interpolation (D 2.108+):

int age = 36;
string name = "Ada";
writeln(i"$(name) is $(age)");

For older D, use format:

import std.format : format;
auto msg = format("%s is %d", name, age);

Common operations (via std.string)

import std.string;

"Hello".toUpper     // "HELLO"
"Hello".toLower     // "hello"
"  hi  ".strip      // "hi"
"abc".indexOf('b')  // 1
"hello world".split(" ")    // ["hello", "world"]
["a", "b"].join("-")        // "a-b"
"banana".replace("a", "o")  // "bonono"

Slicing

Strings (and all arrays) support D's slice syntax:

string s = "hello world";
s[0..5]         // "hello"
s[6..$]         // "world"  ($ is length)
s[$-5..$]       // "world" (last 5 chars)

Iteration

Beware: iterating a string yields char (UTF-8 code units), not characters. For grapheme-correct iteration, use byCodePoint or byGrapheme:

import std.uni;
foreach (c; "héllo".byCodePoint) writeln(c);

For most ASCII code, plain iteration is fine.

to!Type for conversion

import std.conv : to;
int n = "42".to!int;
string s = (3.14).to!string;

Throws ConvException on failure.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…