Use the insert method.
info.insert(19, Misc.toTimestampLiteral(currentDate));
Answer from user425367 on Stack Overflowstring - java: use StringBuilder to insert at the beginning - Stack Overflow
Appending character at the front in the StringBuilder
just do a .reverse on the sb.toString() at the end.. surely that's 10x more readable
More on reddit.comNot sure how to go about changing characters at an index of a string
[Java] What exactly is stringBuilder and why use it instead of a traditional String?
Videos
I have this piece of code
StringBuilder sb = new StringBuilder(); if(strX.charAt(i-1)==strY.charAt(j-1)){ sb.insert(0,strX.charAt(i-1)); }
I get error on the HackerRank that terminated due to timeout. If I remove this piece of code, everything else works fine.
I was wondering if
-
this is the optimized way to keep on appending characters at the front?
-
Does this approach work?
just do a .reverse on the sb.toString() at the end.. surely that's 10x more readable
-
Inserting at index 0 has a time complexity of O(n). So if you already have 500 characters in the internal array, it needs to shift those 500 chars over just to make space for the new char at the first index. So no, it is not.
-
Yes, it works.
Do what OffbeatDrizzle suggests, or simply create a function that will iterate over the StringBuilder in reverse and print out the contents- assuming this is what is required. If you need an object then reversing it at the end is the best way.
// DO NOT DO THIS. It is quadratic-time!
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
Warning: It defeats the purpose of StringBuilder, but it does what you asked.
Better technique (although still not ideal):
- Reverse each string you want to insert.
- Append each string to a
StringBuilder. - Reverse the entire
StringBuilderwhen you're done.
This will turn an O(n²) solution into O(n).
you can use strbuilder.insert(0,i);