Search code examples
d

Replacing elements in an array (string) programmatically


Does D's phobos library provide a function similar to std.array.replace that can replace elements in an array via a function rather than a single value for all replacements? For example:

string[] params = ["Apple", "Orange", "Pear"];
int pnum = 0;
string psub() {
    if (pnum < params.length)
        return params[pnum++];
    return "";
}
writeln(replace("Test 1=? 2=? 3=? 4=?", "?", psub));

results in Test 1=Apple 2=Apple 3=Apple 4=Apple when the desired result is of course Test 1=Apple 2=Orange 3=Pear 4=


Solution

  • You can use replaceAll from std.regex:

    writeln(replaceAll!(s => psub())("Test 1=? 2=? 3=? 4=?", `\?`));
    

    Alternatively, you could use splitter and ranges:

    zip(StoppingPolicy.longest, "Test 1=? 2=? 3=? 4=?".splitter("?"), params)
        .map!(a => only(a.expand))
        .joiner()
        .joiner()
        .writeln();