char[][] join ==> string

Ali Çehreli acehreli at yahoo.com
Wed Apr 6 18:07:10 PDT 2011


On 04/06/2011 05:13 PM, bearophile wrote:
 > Given an array of strings std.string.join() returns a single string:
 >
 > import std.string;
 > void main() {
 >      string[] a1 = ["hello", "red"];
 >      string j1 = join(a1, " "); // OK
 > }
 >
 >
 > But in a program I need an array of mutable arrays of chars. If I 
join the arrays I get a mutable array of chars. But I need a string:

Tangentially off-topic: This does not apply to your case, but I think we 
should think twice before deciding that we need a string. For example, 
functions parameters should be const(char[]) (or const(char)[]) instead 
of string as that type accepts both mutable and immutable strings.

 >
 > import std.string;
 > void main() {
 >      char[][] a2 = ["hello".dup, "red".dup];
 >      string j2 = join(a2, " "); // error

If possible, this might work:

     const(char[]) j2 = join(a2, " ");

There is also std.exception.assumeUnique, but it's too eager to be safe 
and tries to null its parameter and this fails:

     string j2 = assumeUnique(join(a2, " ")); // error

Finally, casting ourselves works:

     string j2 = cast(string)join(a2, " ");

 > }
 >
 > Error: cannot implicitly convert expression (join(a," ")) of type 
char[] to string
 >
 > ..idup avoids the error:
 >
 > string j3 = join(a2, " ").idup; // OK
 >
 > Given the low efficiency of the D GC it's better to reduce memory 
allocations as much as possible.
 > Here join() creates a brand new array, so idup performs a useless 
copy. To avoid this extra copy do I have to write another joinString() 
function?
 >
 > Bye,
 > bearophile

Ali



More information about the Digitalmars-d-learn mailing list