string concatenation

Steven Schveighoffer schveiguy at yahoo.com
Mon Apr 9 09:26:25 PDT 2012


On Sun, 08 Apr 2012 01:08:09 -0400, dnewbie <run3 at myopera.com> wrote:

> I have a wchar[] and I want to convert it to UTF8
> then append a string. This is my code.
>
> import std.c.windows.windows;
> import std.string;
> import std.utf;
>
> int main()
> {
>    wchar[100] v;
>    v[0] = 'H';
>    v[1] = 'e';
>    v[2] = 'l';
>    v[3] = 'l';
>    v[4] = 'o';
>    v[5] = 0;

D does not use null terminated strings, so...

>    string s = toUTF8(v) ~ ", world!";

a fixed-sized wchar array is always passed full-bore.  What you are doing  
is appending ", world!" to a 100-element char array.

The resulting string is:
Hello\0\xff\xff\xff....\xff\xff, world
where that xff represnts the octet 0xff as a char, to fill out the 100  
elements.

So what you want is a slice of the original string, use v[0..n] where n is  
the length of the string.  Since you don't need that 0, you can just do  
v[0..5]:

string s = toUTF8(v[0..5]) ~ ", world!";

>    MessageBoxA(null, s.toStringz, "myapp", MB_OK);
>    return 0;
> }
>
> I want "Hello, world!", but the result is "Hello" only. Please help me.

Yeah, that's what I would have expected.  MessageBox is hitting that 0  
embedded in the string and stopping.

-Steve


More information about the Digitalmars-d-learn mailing list