Re: How to erase chars from char[]?

2010-06-21 Thread Andrei Alexandrescu

On 06/21/2010 06:43 AM, Ben Hanson wrote:

I've changed the code to use CharT[] again, which simplified things
substantially. However, I can't find a way to erase characters from a char[].
Can anyone help?


http://www.digitalmars.com/d/2.0/phobos/std_array.html#replace

Andrei


Re: How to erase chars from char[]?

2010-06-21 Thread bearophile
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