String view
Daniel Keep
daniel.keep+lists at gmail.com
Sun Jan 21 21:31:15 PST 2007
Lionello Lunesu wrote:
> char* p = ....;
> char[] stringview = p[0..strlen(p)];
> assert( stringview.ptr is p );
>
> "NN" <nn-mail at bk.ru> wrote in message
> news:ep0ic7$1a9c$1 at digitaldaemon.com...
>
>>Why there is no string view in D ?
>>
>>Assume I have pointer in memory pointing to zero ending string:
>>char* p;
>>
>>I want to create a string from it but i do not want to copy it.
>>Assume I have a special class for this:
>>StringView s(p);
>>
>>But what would I do if function receives char[] ? There will be a copy.
>>What if I do not want a copy ?
>>
>>Thanx.
A more in-depth explanation:
D has "slices" which are a combination of a pointer and a length (number
of elements). Slices are effectively the same thing as arrays (they
work in precisely the same way).
You can take a slice of an array, *or* a pointer using the
ptr[first..(last+1)]
syntax. The reason you use the last index you want to slice + 1 is that
this allows things like
ptr[0..0]
for an empty slice and
arr[0..$]
which is a slice over an entire array (where "$" is the array's length).
So, in your example, to convert a null-terminated C string into a D
array (WITHOUT copying), you would use the code Lionello posted. Just
note that by doing so, you strip off the trailing NULL (D doesn't use
trailing NULLs since all arrays know their own bounds).
-- Daniel
More information about the Digitalmars-d
mailing list