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

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.

This question is related to java string

The answer is


 String toAdd = "toAdd";
 StringBuilder s = new StringBuilder();
 for(int count = 0; count < MAX; count++) {
     s.append(toAdd);
  }
  String output = s.toString();

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.


Use this:

String input = "original";
String newStr = "new"; //new string to be added
int n = 10 // no of times we want to add
input = input + new String(new char[n]).replace("\0", newStr);

To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.

public static String repeat(char what, int howmany) {
    char[] chars = new char[howmany];
    Arrays.fill(chars, what);
    return new String(chars);
}

and

public static String repeatSB(char what, int howmany) {
    StringBuilder out = new StringBuilder(howmany);
    for (int i = 0; i < howmany; i++)
        out.append(what);
    return out.toString();
}

using

public static void main(String... args) {
    String res;
    long time;

    for (int j = 0; j < 1000; j++) {
        res = repeat(' ', 100000);
        res = repeatSB(' ', 100000);
    }
    time = System.nanoTime();
    res = repeat(' ', 100000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeat: " + time);

    time = System.nanoTime();
    res = repeatSB(' ', 100000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatSB: " + time);
}

(note the loop in main function is to kick in JIT)

The results are as follows:

elapsed repeat: 65899
elapsed repeatSB: 305171

It is a huge difference


You can use Guava's Strings.repeat method:

String existingString = ...
existingString += Strings.repeat("foo", n);

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.


public String appendNewStringToExisting(String exisitingString, String newString, int number) {
    StringBuilder builder = new StringBuilder(exisitingString);
    for(int iDx = 0; iDx < number; iDx++){
        builder.append(newString);
    }
    return builder.toString();
}

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());

Here is a simple way..

for(int i=0;i<n;i++)
{
  yourString = yourString + "what you want to append continiously";
}

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.


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.


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);

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);