问题描述
我正在寻找一种简单的公共方法或运算符,它允许我重复一些字符串 n 次.我知道我可以使用 for 循环来编写它,但我希望在必要时避免 for 循环,并且应该在某处存在一个简单的直接方法.
I'm looking for a simple commons method or operator that allows me to repeat some string n times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");
相关:
重复字符串javascript通过重复给定数量的另一个字符串来创建 NSString次
已编辑
我尽量避免在不是完全必要的情况下使用 for 循环,因为:
I try to avoid for loops when they are not completely necessary because:
即使它们隐藏在另一个函数中,它们也会增加代码行数.
They add to the number of lines of code even if they are tucked away in another function.
有人阅读我的代码必须弄清楚我在那个 for 循环中做了什么.即使它被注释并具有有意义的变量名称,他们仍然必须确保它没有做任何聪明"的事情.
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".
程序员喜欢在 for 循环中加入聪明的东西,即使我写它是为了只做它打算做的事情",但这并不妨碍有人加入并添加一些额外的聪明修复"..
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".
它们通常很容易出错.涉及索引的 For 循环往往会因一个错误而产生.
They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.
For 循环经常重复使用相同的变量,从而增加了很难找到范围错误的机会.
For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.
For 循环增加了 bug 猎人必须查看的位置数量.
For loops increase the number of places a bug hunter has to look.
推荐答案
String::repeat
". ".repeat(7) // Seven period-with-space pairs: . . . . . . .
Java 11 中的新功能 是方法 String::repeat
完全符合您的要求:
New in Java 11 is the method String::repeat
that does exactly what you asked for:
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
*/
这篇关于重复字符串的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!