20

I want to be able to repeat a string of text "n" times:

Something like this -

String "X",
user input = n,
5 = n,
output: XXXXX

I hope this makes sense... (Please be as specific as possible)

arshajii
  • 127,459
  • 24
  • 238
  • 287
user2849489
  • 259
  • 1
  • 2
  • 4

3 Answers3

26
str2 = new String(new char[10]).replace("\0", "hello");

note: this answer was originally posted by user102008 here: Simple way to repeat a String in java

Community
  • 1
  • 1
livanek
  • 261
  • 1
  • 4
  • 3
11

To repeat string n number of times we have a repeat method in Stringutils class from Apache commons.In repeat method we can give the String and number of times the string should repeat and the separator which separates the repeated strings.

Ex: StringUtils.repeat("Hello"," ",2);

returns "Hello Hello"

In the above example we are repeating Hello string two times with space as separator. we can give n number of times in 3 argument and any separator in second argument.

Click here for complete example

membersound
  • 81,582
  • 193
  • 585
  • 1,120
sandeep vanama
  • 689
  • 8
  • 8
6

A simple loop will do the job:

int n = 10;
String in = "foo";

String result = "";
for (int i = 0; i < n; ++i) {
    result += in;
}

or for larger strings or higher values of n:

int n = 100;
String in = "foobarbaz";

// the parameter to StringBuilder is optional, but it's more optimal to tell it
// how much memory to preallocate for the string you're about to built with it.
StringBuilder b = new StringBuilder(n * in.length());
for (int i = 0; i < n; ++i) {
    b.append(in);
}
String result = b.toString();
Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
  • 2
    You should construct your `StringBuilder` with an argument of `n * in.length()`. In any case, +1 – arshajii Oct 05 '13 at 13:02
  • I have no idea how your code is related to what you're asking; also, comments are not the right place to post snippets longer than 1 line. In general, I would recommend learning Java by reading a book or tutorial. Also, it's not good practice to keep asking more and more questions after people have already answered your original question. – Erik Kaplun Oct 05 '13 at 13:31
  • Again: that's actually a new question, first of all; and secondly, that's such a trivial task that if you're not able to solve that independently, you **REALLY** should read a Java book or tutorial first. (...or any other programming language for that matter) – Erik Kaplun Oct 05 '13 at 13:33