On Tuesday, 14 December 2021 at 08:07:43 UTC, WebFreak001 wrote:

The best way would be not doing this at all - when you manipulate strings/arrays in D you can do so by just assigning the elements like this:

```d
immutable(char)[] replaceChar(char[] str, char ch1, char ch2)
{
    for (ulong i = 0; i < len; i++)
    {
        if (str[i] == ch1)
        {
            writefln("Found %c at str[%d]", ch1, i); // fine
            str[i] = ch2;
        }
    }

    return str.idup;
}
```

then when you call it:
```d
replaceChar(str.dup, ';', 'X');
```

or the function more idiomatically:
```d
string replaceChar(scope char[] str, char ch1, char ch2)
{
// ref makes the `c` variable an l-value / assignable and modifies the character when assigned
    foreach (i, ref c; str)
    {
        if (c == ch1)
        {
            writefln("Found %s at str[%s]", c, i);
            c = ch2;
        }
    }

return str.idup; // you could also not .idup and return char[] and let the caller .idup it when needed
}
```

You only really need to work with pointers when you interface with a C library that needs them.

This was of course just me 'playing around with pointer casting in D', and not code that I would have deployed. Debugging that code used up an hour of my life .. that I cannot get back

I might try out @safe instead ;-)



Reply via email to