49

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.

7
  • 3
    What's wrong with a for loop? Commented Dec 7, 2011 at 11:28
  • 1
    Are you looking for one method? there isn't one. Commented Dec 7, 2011 at 11:30
  • 2
    I couldn´t find anything in String, Stringbuilder ... I'm sure you haven't seen append(str) method of StringBuilder or + concat operation of String. Commented Dec 7, 2011 at 11:30
  • 1
    Yes for one or a chain of mehtods, I´d like to avoid the loop ;) Commented Dec 7, 2011 at 11:31
  • 5
    Sure it uses a loop, but I don`t create my own methods if there are already some. Commented Dec 7, 2011 at 11:51

15 Answers 15

50

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.

Sign up to request clarification or add additional context in comments.

1 Comment

48

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.

1 Comment

Gotta love single-line solutions. +1
35

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

Comments

32

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

1 Comment

This might be one of the most efficient ways and can still be written in three lines.
16

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

2 Comments

I am sure the "`"-Symbol is not right at the end of line 4... ;)
Why the new char[n]? Shouldn't it be new char[n*newStr.length()]?
11

You can use Guava's Strings.repeat method:

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

Comments

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

Comments

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.

Comments

3

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

Comments

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

2 Comments

I think you didn't mean to have "existingString" in quotes. Right? You meant to pass the argument in there.
yeah, without IDE sometimes :)
1
 String toAdd = "toAdd";
 StringBuilder s = new StringBuilder();
 for(int count = 0; count < MAX; count++) {
     s.append(toAdd);
  }
  String output = s.toString();

Comments

0

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.

2 Comments

you mean this is more efficient?
Yes, it is much more efficient for operations where you do many appends to the original String, or simply when you're building a String through the concatenation of several sub-strings. ensta-paristech.fr/~diam/java/online/notes-java/data/strings/… read the bit on efficiency.
0

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

1 Comment

That’s quite similar to sudocodes answer.
0

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

Comments

-2

Here is a simple way..

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

1 Comment

You should use StringBuilder in a loop, because string concatenation in a loop is O(xn^2)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.