如何在java中重复字符串“n”次?

时间:2013-10-05 12:55:09

标签: java loops for-loop

我希望能够“n”次重复一串文字:

像这样 -

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

我希望这是有道理的...... (请尽可能具体)

3 个答案:

答案 0 :(得分:23)

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

注意:此答案最初由user102008发布:Simple way to repeat a String in java

答案 1 :(得分:10)

要重复字符串n次,我们在Apache commons的Stringutils类中有一个重复方法。在重复方法中,我们可以给出字符串和字符串重复的次数以及分隔重复字符串的分隔符

例如:StringUtils.repeat("Hello"," ",2);

返回" Hello Hello"

在上面的例子中,我们重复Hello字符串两次,空格作为分隔符。我们可以在3个参数中给出n次,在第二个参数中给出任何分隔符。

Click here for complete example

答案 2 :(得分:6)

一个简单的循环将完成这项工作:

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

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

或更大字符串或更高值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 += 1) {
    b.append(in);
}
String result = b.toString();