Skip to content

Core\Str::repeat

Returns a string written a number of times, one copy after the other.

Core\Str::repeat takes a string and a count, and returns one string that contains that many copies: repeat("ab", 3) gives "ababab". A count of 0, or an empty string, gives "".

The count is a uint, so it can never be negative. A very large count can ask for more memory than the program may use. Then the program stops at its memory limit with an error. A result larger than any process can hold throws a RuntimeError instead.

Programs use it to draw lines and bars in a terminal, and to indent text by a depth.

Parameters

  • $sstringThe string to repeat.
  • $timesuintHow many copies to write.

Return value

Returns string. The repeated string. It is "" when $times is 0 or $s is empty.

Errors

  • RuntimeErrorThe result would be larger than this process can hold.

Examples

A line under a title

<?nvs
// Shows how to draw a line under a title that is exactly as long as the title.
string $title = 'Monthly report';
// `Core\Str::repeat` returns 14 copies of `=`, one for each character of the title.
echo $title, "\n";
echo Core\Str::repeat('=', Core\Str::length($title)), "\n";
Output
Monthly report
==============

Indent by depth

<?nvs
// Shows how to indent lines by their depth in a tree of folders.
array<uint> $folders = ['src' => 0, 'http' => 1, 'routes' => 2, 'tests' => 0];
// Each level adds two spaces. At depth 0, `Core\Str::repeat` returns `""`.
foreach ($folders as string $name => uint $depth) {
echo Core\Str::repeat(' ', $depth), $name, "/\n";
}
Output
src/
http/
routes/
tests/

A bar chart

<?nvs
// Shows how to print a simple bar chart of sales in a terminal.
array<uint> $sales = ['Mon' => 4, 'Tue' => 9, 'Wed' => 6];
// Each `#` is one sale. This prints a bar of 4, 9 and 6 signs.
foreach ($sales as string $day => uint $count) {
echo $day, ' ', Core\Str::repeat('#', $count), ' ', $count, "\n";
}
Output
Mon #### 4
Tue ######### 9
Wed ###### 6