Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating a string in Java - similar to Python's one line simplicity [duplicate]

Tags:

java

string

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

str1 = "hello"
str2 = str1 * 10

string 2 now has the value:

#str2 == 'hellohellohellohellohellohellohellohellohellohello'

I was wondering what the simplest way is to achieve this in java. Do I have to use a for loop or is there a built in method?

EDIT 1

Thanks for your responses I have since 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: https://stackoverflow.com/a/4903603

like image 989
Alec Hewitt Avatar asked Mar 05 '13 14:03

Alec Hewitt


3 Answers

Although not built-in, Guava has a short way of doing this using Strings:

str2 = Strings.repeat("hello", 10);
like image 193
Reimeus Avatar answered Oct 19 '22 09:10

Reimeus


You can use a StringBuffer.

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

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

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

like image 40
wei2912 Avatar answered Oct 19 '22 08:10

wei2912


The for loop is probably your best bet here:

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

If you are doing a lot of iterations (in the 100+ range) consider the use of a StringBuilder object as each time you modify the string you are allocating new memory and releasing the old string for garbage collection. In cases where you are doing this a considerable amount of times it will be a performance issue.

like image 43
Grambot Avatar answered Oct 19 '22 09:10

Grambot