在Java中重复一个字符串 - 类似于Python的单行简单性

时间:2013-03-05 14:49:08

标签: java string

我是来自python的java的新手。 我想知道如何在java中乘以一个字符串。 在python中我会这样做:

str1 = "hello"
str2 = str1 * 10

字符串2现在具有值:

#str2 == 'hellohellohellohellohellohellohellohellohellohello'

我想知道在java中实现这个的最简单方法是什么。我是否必须使用for循环或是否有内置方法?

编辑1

感谢您的回复我已经找到了解决问题的优雅方法:

str2 = new String(new char[10]).replace("\0", "hello");

注意:此答案最初由user102008发布:https://stackoverflow.com/a/4903603

4 个答案:

答案 0 :(得分:9)

虽然没有内置,但Guava使用Strings

的方法很简单
str2 = Strings.repeat("hello", 10);

答案 1 :(得分:3)

您可以使用StringBuffer。

String str1 = "hello";
StringBuffer buffer = new StringBuffer(str1);
for (int i = 0; i < 10; i++) {
    buffer.append(str1);
}
str2 = buffer.toString();

有关文档,请参阅http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/StringBuffer.html

如果您不打算使用任何线程,则可以使用StringBuilder哪种工作方式与StringBuffer相同,但不是线程安全的。有关详细信息,请参阅http://javahowto.blogspot.ca/2006/08/stringbuilder-vs-stringbuffer.html(感谢TheCapn)

答案 2 :(得分:2)

for循环可能是你最好的选择:

for (int i = 0; i < 10; i++)
  str2 += "hello";

如果您正在进行大量迭代(在100+范围内),请考虑使用StringBuilder对象,因为每次修改字符串时,您都要分配新内存并释放旧字符串以进行垃圾回收。如果你这么做很多次,那将是性能问题。

答案 3 :(得分:0)

如果没有某种循环,我认为没有办法做到这一点。

例如:

String result = "";
for (int i=0; i<10; i++){
    result += "hello";
}