Strings and Unicode
8.1 String Types
Strings are arrays, so slicing, ~, .length, and foreach all work. .length is in code units (bytes for string).
string s = "Hello, D!";
writeln(s.length, " ", s[0], " ", s[0 .. 5], " ", s[$ - 2 .. $]);
string t = s ~ " Rocks";
char[] mut = s.dup; // mutable copy
mut[0] = 'J';
string back = mut.idup; // immutable copy8.2 std.string and std.algorithm
import std.string, std.algorithm, std.array, std.uni;
writeln(" hi ".strip, "abc".toUpper, "ABC".toLower, "hello world".capitalize);
writeln("a,b,c".split(","), ["a", "b"].join("-"));
writeln("hello".indexOf("ll"), "hello".startsWith("he"), "hello".endsWith("lo"));
writeln("hello".canFind("ell"), "banana".count("a"));
writeln("hello".replace("l", "L"), "abc".replicate(3));
writeln("x".rightJustify(5), "x".leftJustify(5, '.'), "x".center(5));
writeln("line1\nline2".splitLines, "a b c".split);
writeln("%s is %d".format("D", 2));
writeln("hello".representation); // immutable(ubyte)[]8.3 Formatting
import std.format, std.stdio;
writefln("%s %d %5.2f %x %o %b %e %08d %-10s|", "s", 42, 3.14159, 255, 8, 5, 1e6, 7, "left");
string f = format("%s scored %d", "Ana", 95);
writefln("%(%s, %)", [1, 2, 3]); // range formatting: 1, 2, 3
writefln("%-(%s%)", ["a", "b"]);
writeln(i"Name: $(name), age $(age)"); // interpolation (2.108+)
import std.conv : text;
string t = text("Value: ", 42, " ", 3.5);8.4 Unicode Handling
Autodecoding: Phobos range functions treat string as a range of dchar (they decode automatically). Use .byCodeUnit / .representation for byte-level performance.
import std.utf, std.uni, std.range;
string s = "héllo 🌍";
writeln(s.length); // bytes
writeln(s.walkLength); // code points (auto-decoding)
writeln(s.byGrapheme.walkLength); // user-perceived characters
foreach (dchar c; s) write(c); // decoded iteration
writeln(s.byCodeUnit.length); // no decoding
writeln(toUpper("straße"));
writeln(s.validate); // throws on invalid UTF8.5 String Building and Regular Expressions
import std.array : appender;
auto app = appender!string;
app.put("Hello");
app ~= ", World";
writeln(app[]);
import std.regex;
auto re = regex(r"(\d{4})-(\d{2})-(\d{2})");
if (auto m = "2025-10-24".matchFirst(re)) writeln(m[1], "/", m[2]);
foreach (m; "a1b22c333".matchAll(r"\d+")) writeln(m.hit);
writeln("hello world".replaceAll(regex("o"), "0"));
auto ctr = ctRegex!`^\w+@\w+\.\w+$`; // compile-time regex (fast)