char[][] join ==> string

spir denis.spir at gmail.com
Thu Apr 7 01:04:04 PDT 2011


On 04/07/2011 09:52 AM, spir wrote:
> 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).

After some more thought, I guess it's better to leave things as are. We have a 
way to cast without copy --which is one issue perfectly solved. The other issue 
--typing-- is small enough to keep it, since it also serves as warning to the 
programmer about the above trap.
What should definitely be done is teaching this idiom in all relevant places of 
the reference, manuals, tutorials: while this issue is often submitted on D 
lists, I had never read about it (nore thought about it myself).

Questions: did you know this idiom? if yes, have you found it yourself or read 
about it? if the latter, where?

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



More information about the Digitalmars-d-learn mailing list