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


当前回答

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

Strings.repeat("-", 60);

其他回答

如果你使用的是Java <= 7,这是最“简洁”的:

// create a string made up of n copies of string s
String.format("%0" + n + "d", 0).replace("0", s);

在Java 8及以上版本中,有一种更易读的方式:

// create a string made up of n copies of string s
String.join("", Collections.nCopies(n, s));

最后,对于Java 11及以上版本,有一个专门用于此目的的新的repeat (int count)方法(链接)

"abc".repeat(12);

或者,如果您的项目使用java库,则有更多的选项。

对于Apache Commons:

StringUtils.repeat("abc", 12);

谷歌番石榴:

Strings.repeat("abc", 12);

基于fortran的答案,这是一个使用StringBuilder的递归版本:

public static void repeat(StringBuilder stringBuilder, String s, int times) {
    if (times > 0) {
        repeat(stringBuilder.append(s), s, times - 1);
    }
}

public static String repeat(String s, int times) {
    StringBuilder stringBuilder = new StringBuilder(s.length() * times);
    repeat(stringBuilder, s, times);
    return stringBuilder.toString();
}

如果您关心的是速度,那么应该尽可能少地使用内存复制。因此,它需要处理字符数组。

public static String repeatString(String what, int howmany) {
    char[] pattern = what.toCharArray();
    char[] res = new char[howmany * pattern.length];
    int length = pattern.length;
    for (int i = 0; i < howmany; i++)
        System.arraycopy(pattern, 0, res, i * length, length);
    return new String(res);
}

为了测试速度,使用StirngBuilder的一个类似的优化方法如下:

public static String repeatStringSB(String what, int howmany) {
    StringBuilder out = new StringBuilder(what.length() * howmany);
    for (int i = 0; i < howmany; i++)
        out.append(what);
    return out.toString();
}

以及测试它的代码:

public static void main(String... args) {
    String res;
    long time;

    for (int j = 0; j < 1000; j++) {
        res = repeatString("123", 100000);
        res = repeatStringSB("123", 100000);
    }

    time = System.nanoTime();
    res = repeatString("123", 1000000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatString: " + time);

    time = System.nanoTime();
    res = repeatStringSB("123", 1000000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatStringSB: " + time);

}

下面是我的系统的运行结果:

elapsed repeatString: 6006571
elapsed repeatStringSB: 9064937

注意,for循环测试是为了引入JIT并获得最佳结果。

下面是最短的版本(需要Java 1.5+):

repeated = new String(new char[n]).replace("\0", s);

其中n是你想要重复字符串的次数,s是要重复的字符串。

不需要导入或库。

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

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