How to use `format` to repeat a character
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jul 11 02:31:49 PDT 2016
On 07/11/2016 02:02 AM, Bahman Movaqar wrote:
> I'm sure I'm missing something very simple but how can I create a string
> like "----" using `format`?
You can't.
> I check the docs on `format` and tried many variations including
> `format("%.*c\n", 4, '-')` but got nowhere.
What makes you expect that format should have that feature? :) Perhaps
you're familiar with another language's standard library that does that?
> I'd appreciate any hint/help on this.
There are several ways of repeating characters and range elements in
general:
void main() {
// 'replicate' copies an array (which strings are) eagerly
import std.array : replicate;
assert("-".replicate(3) == "---");
// 'repeat' repeats lazily
import std.range : repeat;
import std.algorithm : equal;
assert('-'.repeat(3).equal("---"));
// Another one that combines multiple range algorithms
import std.range : iota;
import std.algorithm : map;
assert(7.iota.map!(i => i % 2 ? '=' : '-').equal("-=-=-=-"));
// etc.
}
Ali
More information about the Digitalmars-d-learn
mailing list