I could only do this with String, for example:
String str=""; for(int i=0;i<100;i++){ str=i+str; }
Is there a way to achieve this with StringBuilder? Thanks.
Reverse each string you want to insert. Append each string to a StringBuilder . Reverse the entire StringBuilder when you're done.
insert(int offset, char c) method inserts the string representation of the char argument into this sequence. The second argument is inserted into the contents of this sequence at the position indicated by offset. The length of this sequence increases by one.
append(char c) method appends the string representation of the char argument to this sequence. The argument is appended to the contents of this sequence. The length of this sequence increases by 1.
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):
StringBuilder
.StringBuilder
when you're done.This will turn an O(n²) solution into O(n).
you can use strbuilder.insert(0,i);
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