Building a string from n chars

Cassio Butrico via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 3 15:34:32 PDT 2014


On Wednesday, 3 September 2014 at 20:46:40 UTC, monarch_dodra 
wrote:
> On Wednesday, 3 September 2014 at 19:43:26 UTC, Nordlöw wrote:
>> Is there a simpler way to way to
>>
>> s ~= repeat('*', n).array.to!string;
>>
>> if s has to be of type string?
>
> s ~= repeat('*', n).array();
>
> Should be enough. Why the "to!string"?
>
> There's 1 useless allocation, but I think that's OK for code 
> this trivial?
>
> Else, you can do:
> s.length+=n;
> s[$-n .. $] []= '*';
>
> This is also relatively simple. The ownside is doing double 
> assignement, as "length" will initialize new elements to 
> "char.init". Probably not noticeable.
>
> There *might* be more "efficient" ways to do it, but I'd doubt 
> it qualifies as "simpler". Or if it's really observeable. Are 
> these good enough for you?

hello Nordlöw a time I did something like that, see.
string repet(string a, int i)
	{
		int b;
		string c;
		for(b=0;b<=i;b++)
		{c ~= a;}
		return c;
	}

can be adapted to char[].


More information about the Digitalmars-d-learn mailing list