Same process to different results?

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 1 10:40:55 PDT 2015


On Wednesday, 1 July 2015 at 17:13:03 UTC, Taylor Hillegeist 
wrote:
>   string q = cast(string)
>   (A.cycle.take(seg1len).array
>   ~B.cycle.take(seg2len).array
>   ~C.cycle.take(seg3len).array);
>   q.writeln;
>
> I was wondering if it might be the cast?

Yes, the cast is wrong. You're reinterpreting (not converting) an 
array of `dchar`s (UTF-32 code units) as an array of `char`s 
(UTF-8 code units).

If you print the numeric values of the string, e.g. via 
std.string.representation, you can see that every actual 
character has three null bytes following it:
----
import std.string: representation;
writeln(q.representation);
----
[65, 0, 0, 0, 97, 0, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 97, 0, 0, 0, 
65, 0, 0, 0, 65, 0, 0, 0, 97, 0, 0, 0, 65, 0, 0, 0, 65, 0, 0, 0, 
66, 0, 0, 0, 98, 0, 0, 0, 66, 0, 0, 0, 98, 0, 0, 0, 67, 0, 0, 0, 
99, 0, 0, 0, 67, 0, 0, 0, 99, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 
99, 0, 0, 0, 67, 0, 0, 0, 99, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0]
----

Use std.conv.to for less surprising conversions. And don't use 
casts unless you know exactly what you're doing.


More information about the Digitalmars-d-learn mailing list