我正在寻找一个简单的公共方法或操作符,允许我重复一些字符串n次。我知道我可以使用for循环来写这个,但我希望在必要时避免for循环,并且应该在某个地方存在一个简单的直接方法。
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");
相关:
重复字符串javascript
通过重复给定次数的另一个字符串创建NSString
编辑
当它们不是完全必要的时候,我尽量避免使用for循环,因为:
They add to the number of lines of code even if they are tucked away in another function.
Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".
Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".
They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.
For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.
For loops increase the number of places a bug hunter has to look.
合并以供快速参考:
public class StringRepeat {
// Java 11 has built-in method - str.repeat(3);
// Apache - StringUtils.repeat(3);
// Google - Strings.repeat("",n);
// System.arraycopy
static String repeat_StringBuilderAppend(String str, int n) {
if (str == null || str.isEmpty())
return str;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(str);
}
return sb.toString();
}
static String repeat_ArraysFill(String str, int n) {
String[] strs = new String[n];
Arrays.fill(strs, str);
return Arrays.toString(strs).replaceAll("\\[|\\]|,| ", "");
}
static String repeat_Recursion(String str, int n) {
if (n <= 0)
return "";
else
return str + repeat_Recursion(str, n - 1);
}
static String repeat_format1(String str, int n) {
return String.format(String.format("%%%ds", n), " ").replace(" ", str);
}
static String repeat_format2(String str, int n) {
return new String(new char[n]).replace("\0", str);
}
static String repeat_format3(String str, int n) {
return String.format("%0" + n + "d", 0).replace("0", str);
}
static String repeat_join(String str, int n) {
return String.join("", Collections.nCopies(n, str));
}
static String repeat_stream(String str, int n) {
return Stream.generate(() -> str).limit(n).collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(repeat_StringBuilderAppend("Mani", 3));
System.out.println(repeat_ArraysFill("Mani", 3));
System.out.println(repeat_Recursion("Mani", 3));
System.out.println(repeat_format1("Mani", 3));
System.out.println(repeat_format2("Mani", 3));
System.out.println(repeat_format3("Mani", 3));
System.out.println(repeat_join("Mani", 3));
System.out.println(repeat_stream("Mani", 3));
}
}
只使用JRE类(System.arraycopy)并尽量减少临时对象的数量,你可以这样写:
public static String repeat(String toRepeat, int times) {
if (toRepeat == null) {
toRepeat = "";
}
if (times < 0) {
times = 0;
}
final int length = toRepeat.length();
final int total = length * times;
final char[] src = toRepeat.toCharArray();
char[] dst = new char[total];
for (int i = 0; i < total; i += length) {
System.arraycopy(src, 0, dst, i, length);
}
return String.copyValueOf(dst);
}
EDIT
如果没有循环,你可以尝试:
public static String repeat2(String toRepeat, int times) {
if (toRepeat == null) {
toRepeat = "";
}
if (times < 0) {
times = 0;
}
String[] copies = new String[times];
Arrays.fill(copies, toRepeat);
return Arrays.toString(copies).
replace("[", "").
replace("]", "").
replaceAll(", ", "");
}
编辑2
使用Collections甚至更短:
public static String repeat3(String toRepeat, int times) {
return Collections.nCopies(times, toRepeat).
toString().
replace("[", "").
replace("]", "").
replaceAll(", ", "");
}
然而,我仍然喜欢第一个版本。
这是最新的Stringutils.java
public static String repeat(String str, int repeat) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return repeat(str.charAt(0), repeat);
}
int outputLength = inputLength * repeat;
switch (inputLength) {
case 1 :
return repeat(str.charAt(0), repeat);
case 2 :
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default :
StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
它甚至不需要这么大,可以做成这样,可以复制和粘贴
到项目中的实用程序类中。
public static String repeat(String str, int num) {
int len = num * str.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < times; i++) {
sb.append(str);
}
return sb.toString();
}
所以e5,我认为最好的方法是简单地使用上面提到的代码,或者这里的任何答案。但是如果它是一个小项目,Commons lang就太大了