Java line repeating - seems like Python simplicity

I am new to java coming from python. I am wondering how can I multiply a string in java. In python, I would do the following:

str1 = "hello" str2 = str1 * 10 

line 2 now matters:

 #str2 == 'hellohellohellohellohellohellohellohellohellohello' 

I was wondering what is the easiest way to achieve this in java. Should I use a for loop or is there a built-in method?

EDIT 1

Thank you for your responses. Since then I have found an elegant solution to my problem:

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

Note: this answer was originally posted by user102008 here: stack overflow

+8
java string
source share
4 answers

Although not built-in, Guava has a short way to do this using Strings :

 str2 = Strings.repeat("hello", 10); 
+8
source share

You can use StringBuffer.

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

See http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/StringBuffer.html for documentation.

If you are not going to use any threads, you can use StringBuilder , which works the same as StringBuffer , but is not thread safe. See http://javahowto.blogspot.ca/2006/08/stringbuilder-vs-stringbuffer.html for more details (thanks TheCapn)

+3
source share

The for loop is probably best here:

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

If you are doing many iterations (in the range of 100+), consider using the StringBuilder object like every time you change the line that you allocate new memory and free the old line for garbage collection. In cases where you do this a significant number of times, this will be a performance issue.

+2
source share

I don’t think there is a way to do this without some kind of loop.

For example:

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

All Articles