Java: String - add character n-times [duplicate]

2020-02-26 14:08发布

Is there a simple way to add a character or another String n-times to an existing String? I couldn’t find anything in String, Stringbuilder, etc.

标签: java string
15条回答
beautiful°
2楼-- · 2020-02-26 14:48

In addition to the answers above, you should initialize the StringBuilder with an appropriate capacity, especially that you already know it. For example:

int capacity = existingString.length() + n * appendableString.length();
StringBuilder builder = new StringBuilder(capacity);
查看更多
Bombasti
3楼-- · 2020-02-26 14:50

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.

查看更多
贪生不怕死
4楼-- · 2020-02-26 14:52

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);
查看更多
登录 后发表回答