What should I use for concat string into array in loop?

Seb seb at wilzba.ch
Tue Feb 13 02:20:04 UTC 2018


On Tuesday, 13 February 2018 at 01:56:45 UTC, H. S. Teoh wrote:
> On Tue, Feb 13, 2018 at 01:58:42AM +0000, Marc via 
> Digitalmars-d-learn wrote:
>> appender doesn't support string[] so in such case:
>
> Why not? This seems to work:
>
> 	import std.array;
> 	import std.stdio;
> 	void main() {
> 		auto app = appender!(string[]);
> 		foreach (i; 0 .. 1000) {
> 			app.put("abc");
> 		}
> 		writeln(app.data);
> 	}
>
>
> T

Or simply don't allocate at all:

---
import std.algorithm, std.range, std.stdio;

void main()
{
     "abc".repeat(1000).joiner.writeln;
}
---


https://run.dlang.io/is/ubGZwJ


writeln isn't @nogc atm, but if you want to prove that no 
allocation happens, fallback to printf:

----
import core.stdc.stdio, std.algorithm, std.range, std.stdio;

void main() @nogc
{
     "abc".repeat(1000).each!(s => printf("%.*s", s.length, 
s.ptr));
}
---

https://run.dlang.io/is/V7PWXj


More information about the Digitalmars-d-learn mailing list