How do I translate this bit of code from C(using pointers) to D?
anonymous via Digitalmars-d
digitalmars-d at puremagic.com
Tue Aug 26 14:45:01 PDT 2014
On Tuesday, 26 August 2014 at 20:58:15 UTC, MacAsm wrote:
> string str = "foobaa";
> string prev;
[...]
> prev = str; // <- I want to avoid this string duplication did
> in every move() call
If you're worried that this copies the string data, it doesn't. A
dynamic array (which string is) is a pair of a pointer and a
length, and only those are copied.
> foreach(i; 0 .. n) { // <- improve this is welcome too.
> str.popFront();
> }
You can use std.range.popFrontN: str.popFrontN(n);
Also, there are two (maybe more) subtle differences between the D
code and the C code, of which you may not be aware:
1) The D version assumes UTF8. A char is a UTF8 code unit in D,
whereas in C it's just a byte. In D that would be (u)byte. But
char is fine when you're indeed working on UTF8.
2) The D version decodes to code points (dchar). This means e.g.,
that the D version potentially reaches the end of the string in
fewer `go` calls than the C version.
Finally, the "learn" board [1] would have been a better place for
this post. No turning back now, and it's not a big deal, but
next time maybe post there.
[1] http://forum.dlang.org/group/digitalmars.D.learn
More information about the Digitalmars-d
mailing list