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条回答
一夜七次
2楼-- · 2020-02-26 14:38
for(int i = 0; i < n; i++) {
    existing_string += 'c';
}

but you should use StringBuilder instead, and save memory

int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
    builder.append(" append ");
}

System.out.println(builder.toString());
查看更多
趁早两清
3楼-- · 2020-02-26 14:42

Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).

Something like:

StringBuilder b = new StringBuilder(existing_string);
for(int i = 0; i<n; i++){
    b.append("other_string");
}
return b.toString();

Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.

查看更多
成全新的幸福
4楼-- · 2020-02-26 14:43

Its better to use StringBuilder instead of String because String is an immutable class and it cannot be modified once created: in String each concatenation results in creating a new instance of the String class with the modified string.

查看更多
欢心
5楼-- · 2020-02-26 14:44
 String toAdd = "toAdd";
 StringBuilder s = new StringBuilder();
 for(int count = 0; count < MAX; count++) {
     s.append(toAdd);
  }
  String output = s.toString();
查看更多
Summer. ? 凉城
6楼-- · 2020-02-26 14:45

How I did it:

final int numberOfSpaces = 22;
final char[] spaceArray = new char[numberOfSpaces];
Arrays.fill(spaces, ' ');

Now add it to your StringBuilder

stringBuilder.append(spaceArray);

or String

final String spaces = String.valueOf(spaceArray);
查看更多
\"骚年 ilove
7楼-- · 2020-02-26 14:47

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.

查看更多
登录 后发表回答