如何在java中重复字符串“n”次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19198048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to repeat string "n" times in java?
提问by user2849489
I want to be able to repeat a string of text "n" times:
我希望能够重复一串文本“n”次:
Something like this -
像这样的东西——
String "X", user input = n, 5 = n, output: XXXXX
I hope this makes sense... (Please be as specific as possible)
我希望这是有道理的......(请尽可能具体)
回答by Erik Kaplun
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
:
或对于更大的字符串或更高的值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();
回答by livanek
str2 = new String(new char[10]).replace("##代码##", "hello");
note: this answer was originally posted by user102008 here: Simple way to repeat a String in java
注意:这个答案最初是由 user102008 在这里发布的:Simple way to repeat a String in java
回答by sandeep vanama
To repeat string n number of times we have a repeat method in Stringutilsclass 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.
为了重复字符串 n 次,我们在Apache 公共的Stringutils类中有一个重复方法。在重复方法中,我们可以给出字符串和字符串应该重复的次数以及分隔重复字符串的分隔符。
Ex: StringUtils.repeat("Hello"," ",2);
前任: 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.
在上面的例子中,我们用空格作为分隔符重复了两次 Hello 字符串。我们可以在 3 个参数中给出 n 次,在第二个参数中给出任何分隔符。