how do you append arrays?

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 25 05:06:10 PST 2016


On Thursday, 25 February 2016 at 12:58:54 UTC, Nicholas Wilson 
wrote:
> On Thursday, 25 February 2016 at 12:53:37 UTC, asdf wrote:
>> I'm trying to make a terminal input preprocessor with 
>> alias/shortcuts and history.
>>
>>
>> import std.stdio;
>>
>> void main() {
>>     string line;
>>     string[] history;
>>
>>     line = readln();
>>     foreach(int i; 0..100) history = history + [""]; // XXX
>>
>>     while(!stdin.eof) {
>>         writeln(line);
>>         if(line != history[0]) {
>>             history[1..100] = history[0..99];
>>             history[0] = line;
>>         }
>>         line = readln();
>>     }
>> }
>
> In D the binary operator "~"  is used to concatenate both 
> strings (arrays of characters) and arrays. (also the ~= 
> operator is equivalent to lhs = lhs ~ rhs
>
> Nic

Just a precision:  "lhs ~= rhs" isn't exactly equivalent to "lhs 
= lhs ~ rhs", those are two distinct operators that may deal with 
memory etc in different ways. For arrays doing "lhs = lhs ~ rhs" 
will first create (and allocate) the array corresponding  to "lhs 
~ rhs" and then assign this new array to lhs. On the other hand 
"lhs ~= rhs" realises in-place append.


More information about the Digitalmars-d-learn mailing list