小编典典

在Java中重复字符串的简单方法

java

我在寻找一个简单的方法,公共或操作员,让我再重复一些字符串ñ倍。我知道我可以使用for循环编写此代码,但是我希望在必要时避免for循环,并且应该在某个地方存在一个简单的直接方法。

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

repeated.equals("abcabcabc");

相关:

重复字符串javascript 通过重复给定次数另一个字符串来创建NSString

已编辑

当它们不是完全必要时,我尝试避免for循环,因为:

  1. 即使将它们隐藏在另一个函数中,它们也会增加代码行数。

  2. 读取我的代码的人必须弄清楚我在for循环中正在做什么。即使它被注释并且具有有意义的变量名称,他们仍然必须确保它没有做任何“聪明的事情”。

  3. 程序员喜欢将聪明的东西放入for循环中,即使我将其写为“仅按计划执行”,也不排除有人来添加额外的聪明的“修复”。

  4. 它们通常很容易出错。对于涉及索引的循环,往往会产生一个错误。

  5. For循环通常会重用相同的变量,从而增加了很难发现作用域错误的机会。

  6. 对于循环,增加了寻找漏洞猎人的位置。


阅读 634

收藏
2020-02-25

共2个答案

小编典典

String::repeat

". ".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
 */ 
2020-02-25
小编典典

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

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

在哪里n是你要重复字符串的次数,并且s是要重复的字符串。

无需导入或库。

2020-02-25