Tim:

is there any chance to modify a char in a string like:

void main()
{
   string sMyText = "Replace the last char_";
   sMyText[$ - 1] = '.';
}

But when I execute the code above I'm always getting "cannot modify immutable expression at sMyText[__dollar -1LU]". I though D supported such modifications anytime. How can I do that now...?

D strings are immutable. And mutating immutable variables is a bug in D. So you can't do that. You have to work around the problem. One solution is to not have a string, but something more like a char[] in the first place, and mutate it.

If you have a string, you can do (this works with the current GIT DMD compiler):



/// Not Unicode-safe.
string dotLast(in string s) pure nothrow {
    auto ds = s.dup;
    ds[$ - 1] = '.';
    return ds;
}

void main() {
    import std.stdio;

    immutable input = "Replace the last char_";
    immutable result = input.dotLast;
    result.writeln;
}


That code doesn't work if your text contains more than the Ascii chars.

Bye,
bearophile

Reply via email to