View source code
Display the source code in std/array.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.

std.array.replace - multiple declarations

Function replace

Replace occurrences of from with to in subject in a new array. If sink is defined, then output the new array into sink.

E[] replace(E, R1, R2) (
  E[] subject,
  R1 from,
  R2 to
)
if (isDynamicArray!(E[]) && isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2));

Parameters

NameDescription
sink an output range
subject the array to scan
from the item to replace
to the item to replace all instances of from with

Returns

If sink isn't defined, a new array without changing the contents of subject, or the original array if no match is found.

See Also

substitute for a lazy replace.

Example

writeln("Hello Wörld".replace("o Wö", "o Wo")); // "Hello World"
writeln("Hello Wörld".replace("l", "h")); // "Hehho Wörhd"
Edit
Run
Open in IDE
Application output
Running...

Example

auto arr = [1, 2, 3, 4, 5];
auto from = [2, 3];
auto to = [4, 6];
auto sink = appender!(int[])();

replaceInto(sink, arr, from, to);

writeln(sink.data); // [1, 4, 6, 4, 5]
Edit
Run
Open in IDE
Application output
Running...

Function replace

Replaces elements from array with indices ranging from from (inclusive) to to (exclusive) with the range stuff.

T[] replace(T, Range) (
  T[] subject,
  size_t from,
  size_t to,
  Range stuff
)
if (isInputRange!Range && (is(ElementType!Range : T) || isSomeString!(T[]) && is(ElementType!Range : dchar)));

Parameters

NameDescription
subject the array to scan
from the starting index
to the ending index
stuff the items to replace in-between from and to

Returns

A new array without changing the contents of subject.

See Also

substitute for a lazy replace.

Example

auto a = [ 1, 2, 3, 4 ];
auto b = a.replace(1, 3, [ 9, 9, 9 ]);
writeln(a); // [1, 2, 3, 4]
writeln(b); // [1, 9, 9, 9, 4]
Edit
Run
Open in IDE
Application output
Running...

Authors

Andrei Alexandrescu and Jonathan M Davis

License

Boost License 1.0.