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 using StringBuilder? Thank.

+48
java string stringbuilder insert append
May 09 '11 at
source share
5 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 does what you requested.




The best technique (although not perfect):

  • Flip each row you want to insert.
  • Add each row to StringBuilder .
  • Complete all StringBuilder when done.

This will turn the solution O (nΒ²) into O (n).

+107
May 09 '11 at 12:10 a.m.
source share

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

+18
May 09 '11 at
source share

Maybe I missed something, but you want to end the String string, which looks like this: "999897969594...543210" , right?

 StringBuilder sb = new StringBuilder(); for(int i=99;i>=0;i--){ sb.append(String.valueOf(i)); } 
+7
May 9 '11 at 4:27
source share

As an alternative, you can use a LIFO structure (like a stack) to store all the strings, and when you are done, just pull them all out and put them in a StringBuilder. Naturally, it changes the order of the elements (lines) placed in it.

 Stack<String> textStack = new Stack<String>(); // push the strings to the stack while(!isReadingTextDone()) { String text = readText(); textStack.push(text); } // pop the strings and add to the text builder String builder = new StringBuilder(); while (!textStack.empty()) { builder.append(textStack.pop()); } // get the final string String finalText = builder.toString(); 
+6
Jan 08 '15 at 7:13
source share

This thread is pretty old, but you might also think of a recursive solution that passes StringBuilder to fill. This prevents any back processing, etc. You just need to design your iteration with recursion and carefully solve the exit condition.

 public class Test { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); doRecursive(sb, 100, 0); System.out.println(sb.toString()); } public static void doRecursive(StringBuilder sb, int limit, int index) { if (index < limit) { doRecursive(sb, limit, index + 1); sb.append(Integer.toString(index)); } } } 
+3
Jan 04 '14 at
source share



All Articles