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
Although not built-in, Guava has a short way of doing this using Strings:
str2 = Strings.repeat("hello", 10);
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With