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. template substitute(substs...)
  2. auto substitute(R r, Substs substs)
    substitute
    (
    alias pred =
    (
    a
    ,
    b
    )
    => a == b
    R
    Substs...
    )
    (
    R r
    ,
    Substs substs
    )
    if (
    Substs.length >= 2
    &&
    !is(CommonType!(Substs) == void)
    )

Parameters

r R
substs Substs

a set of replacements/substitutions

pred

the equality function to test if element(s) are equal to a substitution

Return Value

Type: auto

a range with the substitutions replaced.

Examples

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"));

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