Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: use StringBuilder to insert at the beginning

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.

like image 605
user685275 Avatar asked May 09 '11 00:05

user685275


People also ask

How do I add to the beginning of StringBuilder?

Reverse each string you want to insert. Append each string to a StringBuilder . Reverse the entire StringBuilder when you're done.

How does StringBuilder insert work?

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.

How do I add a character to a StringBuilder in Java?

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.


2 Answers

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):

  1. Reverse each string you want to insert.
  2. Append each string to a StringBuilder.
  3. Reverse the entire StringBuilder when you're done.

This will turn an O(n²) solution into O(n).

like image 53
user541686 Avatar answered Sep 19 '22 14:09

user541686


you can use strbuilder.insert(0,i);

like image 37
ratchet freak Avatar answered Sep 19 '22 14:09

ratchet freak