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.

user905686
  • 4,491
  • 8
  • 39
  • 60

15 Answers15

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.

Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
zeller
  • 4,904
  • 2
  • 22
  • 40
45

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.

Xeon
  • 5,949
  • 5
  • 31
  • 52
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(""));
Sa'ad
  • 5,255
  • 2
  • 17
  • 21
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);
ewan.chalmers
  • 16,145
  • 43
  • 60
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);
Foggzie
  • 9,691
  • 1
  • 31
  • 48
js_248
  • 2,032
  • 4
  • 27
  • 38
11

You can use Guava's Strings.repeat method:

String existingString = ...
existingString += Strings.repeat("foo", n);
ColinD
  • 108,630
  • 30
  • 201
  • 202
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());
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90
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.

user905686
  • 4,491
  • 8
  • 39
  • 60
Jimshad Abdulla
  • 167
  • 2
  • 8
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);
Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
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();
}
mprabhat
  • 20,107
  • 7
  • 46
  • 63
1
 String toAdd = "toAdd";
 StringBuilder s = new StringBuilder();
 for(int count = 0; count < MAX; count++) {
     s.append(toAdd);
  }
  String output = s.toString();
Jonno_FTW
  • 8,601
  • 7
  • 58
  • 90
Vicky
  • 16,679
  • 54
  • 139
  • 232
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);
avuton
  • 13
  • 2
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

Panayotis
  • 1,792
  • 23
  • 32
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.

pcalcao
  • 15,789
  • 1
  • 44
  • 64
  • you mean this is more efficient? – user905686 Dec 07 '11 at 11:53
  • 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. http://www.ensta-paristech.fr/~diam/java/online/notes-java/data/strings/23stringbufferetc.html read the bit on efficiency. – pcalcao Dec 07 '11 at 12:34
-2

Here is a simple way..

for(int i=0;i<n;i++)
{
  yourString = yourString + "what you want to append continiously";
}
COD3BOY
  • 11,964
  • 1
  • 38
  • 56