Java: String - add character n-times

Apache commons-lang3 has StringUtils.repeat(String, int), with this one you can do (for simplicity, not with StringBuilder):

String original;
original = original + StringUtils.repeat("x", n);

Since it is open source, you can read how it is written. There is a minor optimalization for small n-s if I remember correctly, but most of the time it uses StringBuilder.


You are able to do this using Java 8 stream APIs. The following code creates the string "cccc" from "c":

String s = "c";
int n = 4;
String sRepeated = IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining(""));

For the case of repeating a single character (not a String), you could use Arrays.fill:

  String original = "original ";
  char c = 'c';
  int number = 9;

  char[] repeat = new char[number];
  Arrays.fill(repeat, c);
  original += new String(repeat);

In case of Java 8 you can do:

int n = 4;
String existing = "...";
String result = existing + String.join("", Collections.nCopies(n, "*"));

Output:

...****

In Java 8 the String.join method was added. But Collections.nCopies is even in Java 5.

Tags:

Java

String