If you don't have the memory to create a new StringBuilder, then you don't have the memory to create a new StringBuilder, and cloning wouldn't change that. The only real way to copy a StringBuilder is new StringBuilder(myBuilder), or something equivalent.
If you're getting OutOfMemoryException, you'll need to either get more memory, or find some other way to reduce memory consumption.
If you don't have the memory to create a new StringBuilder, then you don't have the memory to create a new StringBuilder, and cloning wouldn't change that. The only real way to copy a StringBuilder is new StringBuilder(myBuilder), or something equivalent.
If you're getting OutOfMemoryException, you'll need to either get more memory, or find some other way to reduce memory consumption.
You can clear StringBuilder object by:
1.
sb.delete(0, sb.length())
2.
sb = null;
sb = new StringBuilder();
For performance, 1. is the better option. But you cannot clone it anyway. For more info about clone see
- Shallow copy and Deep Copy
- Clone
I'd just like to make a slight change to the code. When you are instantiating a StringBuilder, you have the opportunity to specify the capacity of it. Using this constructor, we can avoid having it resized more than necessary.
public String frontTimes(String str, int n) {
StringBuilder stringBuilder = new StringBuilder(3 * n);
if (str.length() > 3) {
str = str.substring(0, 3);
}
for (int i = 0; i < n; i++) {
stringBuilder.append(str);
}
return stringBuilder.toString();
}
Note how many times that 3 is declared? Would be better to extract that to a constant, or even better, a parameter. And with a few other changes to the above (as suggested by @rolfl in chat):
public String frontTimes(final String str, final int frontLength, final int times) {
String copyString = str.length() > frontLength ? str.substring(0, frontLength) : str;
StringBuilder stringBuilder = new StringBuilder(copyString.length() * times);
for (int i = 0; i < times; i++) {
stringBuilder.append(copyString);
}
return stringBuilder.toString();
}
I am a fan of using primitives. In this case, the performance benefit would be minimal, but the number of copies would actually be less.....
In reality, I would probably use the StringBuilder approach similar to what other answers have given (+1 to them all), but you should be aware that the following code is likely faster, has fewer iterations through the loop, and will scale better..... if you ever need to make millions of copies... ;-) (now here with a cheesy test case in ideone too)
/**
* Using the input source string, duplicate its prefix the specified count
* times.
* @param source The source string containing the prefix
* @param prefixLength The length of the prefix to use (or the whole string
* if the prefix is larger than the String)
* @param count the number of times to repeat the prefix.
* @return the resulting duplicated string, or an empty string if the source
* is invalid or the count or prefix length is zero
*/
public static String duplicatePrefix(final String source, final int prefixLength, final int count) {
if (source == null || source.length() == 0 || prefixLength <= 0 || count <= 0) {
return "";
}
final int actual = Math.min(source.length(), prefixLength);
final int size = actual * count;
final char[] results = new char[size];
// copy the first prefix to the output
source.getChars(0, actual, results, 0);
// duplicate the previously populated chars as often as needed.
int currentpos = actual;
while (currentpos < size) {
// copy as much as you can, limited by the available space to copy to.
System.arraycopy(results, 0, results, currentpos, Math.min(currentpos, size - currentpos));
// double the current position
currentpos <<= 1;
}
return new String(results);
}
Note that the loop in the above code will iterate only \ times where, which can be a significant saving in the event that
count is large, though the ArrayCopy is still an \ operation, so it is a toss up as to whether it will improve the speed at all... it will need some benchmarking.
What happens when i use toString() method on a StringBuilder?
java - How to copy a String substring to a StringBuilder - Stack Overflow
Convert the string into stringBuilder in java - Stack Overflow
java - How to get character array which is inside StringBuilder to avoid array copy - Stack Overflow
Can StringBuilder Be Serialized?
Can StringBuilder Be Used with Streams?
How Does StringBuilder Handle Null Arguments?
So let's say i have a code like this:-
StringBuilder str = new StringBuilder("hello");
System.out.println(str.toString()); So is it like there are two arrays, StringBuilder and String and we loop StringBuilder and copy it's contents character by character into the String? What would be the time complexity of this process?
use can use constructor of the StringBuilder
StringBuilder builder = new StringBuilder(string.substring(start, end));
String implements CharSequence, so you can use StringBuffer.append(CharSequence s,int start, int end), however I would caution that unless you know that this is likely to be/is a problem, then using this method instead of substring is premature optimization.
To create a StringBuilder from a String simply:
StringBuilder sb = new StringBuilder("MyString");
String s = sb.toString();
But as was said StringBuilder and StringBuffer are different. Take a look here for more information on StringBuilder and StringBuffer
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
Difference between StringBuilder and StringBuffer
Convert String to StringBuilder
String someText = "something...";
StringBuilder sb = new StringBuilder(someText);
Avoid doing stringbuilder.toString().toCharArray() as it will allocate the memory twice.
Use something like :
char[] charArray = new char[stringbuilder.length()];
stringbuilder.getChars(0, stringbuilder.length(), charArray, 0);
Using reflection is also a bad idea as it may not be compatible with future java version and you'll have to resize the array as its size is probably bigger than the StringBuilder length see StringBuilder#capacity()
You can treat the StringBuilder as a char[], the bridge is supported by the interface CharSequnce
Calling the method charAt(int index) is "equal to" array[index]
The array is a private field that is not exposed to the public customer, due to encapsulation.