Search code examples
d

Search and Replace in string in D


I'm writing some code in D and am trying to determine a generic way to search for a string within a string and replace it with another string potentially of a different length.

For example, something that works like this:

string x = "123XX456XX789";
auto y = search_and_replace(x, "XX", "DIFFERENT");
assert (y == "123DIFFERENT456DIFFERENT789");

Solution

  • Easy, the replace function in the standard library does exactly that:

    import std.array; // or std.string works too but std.array has the generic one
    auto y = replace(x, "XX, "DIFFERENT");