substitute

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).

  1. auto substitute(Value value)
    template substitute(substs...)
    substitute
    (
    Value
    )
    (
    Value value
    )
    if (
    isInputRange!Value ||
    !is(CommonType!(Value, typeof(substs[0])) == void)
    )
    if (
    substs.length >= 2 &&
    )
  2. auto substitute(R r, Substs substs)

Members

Functions

substitute
auto substitute(Value value)

Substitute single values with compile-time substitution mappings. Complexity: O(1) due to D's switch guaranteeing O(1);

Parameters

value

a single value which can be substituted in O(1)

substs

a set of replacements/substitutions

Return Value

a range with the substitutions replaced.

Examples

1 import std.algorithm.comparison : equal;
2 
3 // substitute single elements
4 assert("do_it".substitute('_', ' ').equal("do it"));
5 
6 // substitute multiple, single elements
7 assert("do_it".substitute('_', ' ',
8                            'd', 'g',
9                            'i', 't',
10                            't', 'o')
11               .equal("go to"));
12 
13 // substitute subranges
14 assert("do_it".substitute("_", " ",
15                           "do", "done")
16               .equal("done it"));
17 
18 // substitution works for any ElementType
19 int[] x = [1, 2, 3];
20 auto y = x.substitute(1, 0.1);
21 assert(y.equal([0.1, 2, 3]));
22 static assert(is(typeof(y.front) == double));
23 
24 import std.range : retro;
25 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"));

See Also

std.array.replace for an eager replace algorithm or std.string.translate, and std.string.tr for string algorithms with translation tables.

Meta

Suggestion Box / Bug Report