char[][] join ==> string

spir denis.spir at gmail.com
Thu Apr 7 00:52:59 PDT 2011


On 04/07/2011 03:07 AM, Ali Çehreli 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.
> [...]
> Finally, casting ourselves works:
>
>      string j2 = cast(string)join(a2, " ");

Oh, that's very good news! Thans Ali, I never thought at that solution. I'm 
often i/dup-ing from/to string to manipulate text due to the fact there is no 
automatic conversion.
cast() works in place, doesn't it? so this is supposed avoid to avoid copy.

PS: Checked: indeed, it works in-place. But watch the gotcha:

unittest {
     string s = "abc";
     char[] chars = cast(char[])s;
     chars ~= "de";
     s = cast(string) chars;
     writeln(s, ' ', chars); // abcde abcde

     chars[1] = 'z';
     writeln(s, ' ', chars); // azcde azcde
}

s's chars are mutable ;-) So, I guess there is /really/ no reason for implicite 
casts between char[] and string no to exist. (I assumed the reason was 
precisely to avoid such traps).

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list