Substitute single values with compile-time substitution mappings. Complexity: O(1) due to D's switch guaranteeing O(1);
a range with the substitutions replaced.
import std.algorithm.comparison : equal; // substitute single elements assert("do_it".substitute('_', ' ').equal("do it")); // substitute multiple, single elements assert("do_it".substitute('_', ' ', 'd', 'g', 'i', 't', 't', 'o') .equal("go to")); // substitute subranges assert("do_it".substitute("_", " ", "do", "done") .equal("done it")); // substitution works for any ElementType int[] x = [1, 2, 3]; auto y = x.substitute(1, 0.1); assert(y.equal([0.1, 2, 3])); static assert(is(typeof(y.front) == double)); import std.range : retro; assert([1, 2, 3].substitute(1, 0.1).retro.equal([3, 2, 0.1]));
Use the faster compile-time overload
import std.algorithm.comparison : equal; // substitute subranges of a range assert("apple_tree".substitute!("apple", "banana", "tree", "shrub").equal("banana_shrub")); // substitute subranges of a range assert("apple_tree".substitute!('a', 'b', 't', 'f').equal("bpple_free")); // substitute values assert('a'.substitute!('a', 'b', 't', 'f') == 'b');
Multiple substitutes
import std.algorithm.comparison : equal; import std.range.primitives : ElementType; int[3] x = [1, 2, 3]; auto y = x[].substitute(1, 0.1) .substitute(0.1, 0.2); static assert(is(typeof(y.front) == double)); assert(y.equal([0.2, 2, 3])); auto z = "42".substitute('2', '3') .substitute('3', '1'); static assert(is(ElementType!(typeof(z)) == dchar)); assert(equal(z, "41"));
std.array.replace for an eager replace algorithm or std.string.translate, and std.string.tr for string algorithms with translation tables.
Returns a range with all occurrences of substs in r. replaced with their substitution.
Single value replacements ('ö'.substitute!('ä', 'a', 'ö', 'o', 'ü', 'u)) are supported as well and in O(1).