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

use*_*489 18 java loops for-loop

我想能够"n"次重复一串文字:

像这样的东西 -

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

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

小智 23

str2 = new String(new char[10]).replace("\0", "hello");
Run Code Online (Sandbox Code Playgroud)

注意:这个答案最初由user102008发布:在java中重复String的简单方法


小智 10

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

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

返回"Hello Hello"

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

点击此处查看完整示例

  • 这也是我的首选解决方案,因为它非常易读,特别是在使用分离器时,它有特殊情况需要处理 (2认同)

Eri*_*lun 7

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

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

String result = "";
for (int i = 0; i < n; ++i) {
    result += in;
}
Run Code Online (Sandbox Code Playgroud)

或者对于更大的字符串或更高的值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();
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用`n*in.length()`参数构造`StringBuilder`.在任何情况下,+ 1 (2认同)