View source code
Display the source code in std/algorithm/iteration.d from which this
page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a
Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Template std.algorithm.iteration.substitute
Returns a range with all occurrences of substs
in r
.
replaced with their substitution.
template substitute(substs...)
;
auto substitute(alias pred, R, Substs...)
(
R r,
Substs substs
)
if (isInputRange!R && (Substs .length >= 2) && !is(CommonType!Substs == void));
Single value replacements ('ö'
) are
supported as well and in Ο(1
).
Template substitute
Contained Functions
Name | Description |
---|---|
substitute | Substitute single values with compile-time substitution mappings. |
Function substitute
Parameters
Name | Description |
---|---|
r | an input range |
value | a single value which can be substituted in Ο(1 ) |
substs | a set of replacements/substitutions |
pred | the equality function to test if element(s) are equal to a substitution |
Returns
a range with the substitutions replaced.
See Also
replace
for an eager replace algorithm or
translate
, and tr
for string algorithms with translation tables.
Example
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]));
Example
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
writeln('a' .substitute!('a', 'b', 't', 'f')); // 'b'
Example
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"));
Authors
License
Copyright © 1999-2024 by the D Language Foundation | Page generated by ddox.