我正在寻找一个简单的公共方法或操作符,允许我重复一些字符串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 String repeat(String str, int count){
    if(count <= 0) {return "";}
    return new String(new char[count]).replace("\0", str);
}

其他回答

Commons only StringUtils.repeat()

用法:

String str = "abc";
String repeated = StringUtils.repeat(str, 3);

repeated.equals("abcabcabc");

如果担心性能问题,只需在循环中使用StringBuilder,并在循环退出时执行. tostring()。见鬼,编写自己的Util类并重用它。最多5行代码。

字符串:重复

". ".repeat(7)  // Seven period-with-space pairs: . . . . . . . 

Java 11中的新方法是String::repeat,它完全符合你的要求:

String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");

它的Javadoc说:

/**
 * Returns a string whose value is the concatenation of this
 * string repeated {@code count} times.
 * <p>
 * If this string is empty or count is zero then the empty
 * string is returned.
 *
 * @param count number of times to repeat
 *
 * @return A string composed of this string repeated
 * {@code count} times or the empty string if this
 * string is empty or count is zero
 *
 * @throws IllegalArgumentException if the {@code count} is
 * negative.
 *
 * @since 11
 */ 

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

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

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

如果你使用的是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);