How to erase chars from char[]?

bearophile bearophileHUGS at lycos.com
Mon Jun 21 05:20:05 PDT 2010


Ben Hanson:
> However, I can't find a way to erase characters from a char[].
> Can anyone help?

If you need to delete the last chars you can just decrease the length. If you need to delete chars in the middle you can copy items with memmove() and then decrease the length. You can also write a function to do it, this is just a rough starting point for such function:


import std.range: hasAssignableElements;
import std.c.string: memmove;

/**
this doesn't work with user-defined arrays
it can be made more general, able to work on
Random Access Ranges can can shrink
It can contain a static if that tells apart true D arrays, and uses
memmove() on them, from generic Random Access Ranges, that need a for
loop to copy items.
*/
void remove(T)(ref R[] items, size_t start, size_t stop)
    if (hasAssignableElements!R)
    in {
        assert(stop => start);
        assert(items.length >= start);
        assert(items.length >= stop);
    } out {
        // assert(items.length <= old.items.length); // not doable yet
    } body {
        if (stop == items.length)
            items.length = start;
        else {
            memmove(...);
            items.length = ...
        }
    }

void main() {
    char[] s = "012345678".dup;
    s.remove(2, 4);
    assert(s == "...");
}


Bye,
bearophile


More information about the Digitalmars-d mailing list