我正在寻找一个简单的公共方法或操作符,允许我重复一些字符串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.


当前回答

使用Dollar就像输入一样简单:

@Test
public void repeatString() {
    String string = "abc";
    assertThat($(string).repeat(3).toString(), is("abcabcabc"));
}

PS:重复工作也为数组,列表,集等

其他回答

这里有一种只使用标准String函数而没有显式循环的方法:

// create a string made up of  n  copies of  s
repeated = String.format(String.format("%%%ds", n), " ").replace(" ",s);

使用Dollar就像输入一样简单:

@Test
public void repeatString() {
    String string = "abc";
    assertThat($(string).repeat(3).toString(), is("abcabcabc"));
}

PS:重复工作也为数组,列表,集等

简单的循环

public static String repeat(String string, int times) {
    StringBuilder out = new StringBuilder();
    while (times-- > 0) {
        out.append(string);
    }
    return out.toString();
}

我想要一个函数来为JDBC创建一个以逗号分隔的问号列表,然后找到了这篇文章。所以,我决定采用两个变体,看看哪个表现更好。在100万次迭代之后,普通的StringBuilder花了2秒(fun1),而神秘的最优版本(fun2)花了30秒。又变得神秘有什么意义?

private static String fun1(int size) {
    StringBuilder sb = new StringBuilder(size * 2);
    for (int i = 0; i < size; i++) {
        sb.append(",?");
    }
    return sb.substring(1);
}

private static String fun2(int size) {
    return new String(new char[size]).replaceAll("\0", ",?").substring(1);
}

如果你像我一样想使用谷歌Guava而不是Apache Commons。你可以在Guava Strings类中使用repeat方法。

Strings.repeat("-", 60);