Logo

Programming-Idioms

  • C++
  • Java

Idiom #266 Repeated string

Assign to the string s the value of the string v repeated n times, and write it out.

E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"

for (int i=0;i<n;i++){
          s = s+v;
      }
System.out.println(s);

s+v is the same as s.concat(v) and can be used interchangeably
import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.generate;
String s = generate(() -> v)
    .limit(n)
    .collect(joining());
String s = v.repeat(n);

System.out.println(s);

Java 11+
#include <string>
s.reserve(v.size() * n);
for (size_t i = 0; i < n; ++i)
  s.append(v);
with Ada.Strings.Fixed;
use Ada.Strings.Fixed;
S : constant String := N * V;

New implementation...
< >
tkoenig