java: use StringBuilder to insert at the beginning

183,166

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

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

Solution 2

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

Solution 3

Maybe I'm missing something but you want to wind up with a String that looks like this, "999897969594...543210", correct?

StringBuilder sb = new StringBuilder();
for(int i=99;i>=0;i--){
    sb.append(String.valueOf(i));
}

Solution 4

As an alternative solution you can use a LIFO structure (like a stack) to store all the strings and when you are done just take them all out and put them into the StringBuilder. It naturally reverses the order of the items (strings) 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();

Solution 5

This thread is quite old, but you could also think about a recursive solution passing the StringBuilder to fill. This allows to prevent any reverse processing etc. Just need to design your iteration with a recursion and carefully decide for an 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));
        }
    }
}
Share:
183,166

Related videos on Youtube

user685275
Author by

user685275

Updated on August 06, 2020

Comments

  • user685275
    user685275 almost 4 years

    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.

  • entonio
    entonio about 13 years
    ...since it makes AbstractStringBuilder move all the contents past the index of insertion in order to find room for the inserted ones. However, that's an implementation detail, not one of principle.
  • user541686
    user541686 about 13 years
    @entonio: Indeed, but it's a very critical detail. :)
  • user685275
    user685275 about 13 years
    I see,It looks like I shouldn't be using StringBuilder then, Thanks a lot
  • user541686
    user541686 about 13 years
    @user685275: Yeah, if you need backwards insertion then you really need something that can insert at the beginning of the string. I think the easiest solution is the technique above (reversing things twice), although you could probably make a better class of your own with char arrays (might want to look into "deque"s).
  • nom-mon-ir
    nom-mon-ir over 9 years
    Strange this post did not get much voting while providing the solution by clever manipulation of the loop,
  • Raymond Chenon
    Raymond Chenon over 8 years
    @nom-mon-ir he just reversing the String. It doesn't answer how to append on the left.
  • Speck
    Speck over 8 years
    Achieves the desired effect.
  • Luna
    Luna over 8 years
    ArrayDeque should be used instead of Stack. "A more complete and consistent set of LIFO stack operations is provided by the {@link Deque} interface and its implementations, which should be used in preference to this class. "
  • jorgeu
    jorgeu almost 6 years
    Another option when conditions are right is to use a linked list with addFirst and then use Collectors.joining(...) to create the desired string.
  • user541686
    user541686 almost 6 years
    @jorgeu: It's difficult to overstate how extremely rare it is for a linked list to be a better choice here.
  • jorgeu
    jorgeu almost 6 years
    @Mehrdad you sure you know what string builder is doing when you add at the begining? see stackoverflow.com/questions/26170180/…
  • user541686
    user541686 almost 6 years
    @jorgeu: Yeah. I don't see anything in your link to the contrary either. And see here.
  • PhoneixS
    PhoneixS almost 6 years
    I think that there could be cases in which you can use this approach instead of trying to hack a way to do the insert on the beginning which uses the true potential of StringBuilder. Anyway, there are cases in which you can't reverse the loop so you need also the other answers.
  • Akhil Surapuram
    Akhil Surapuram over 5 years
    @Mehrdad I have tried your Better Technique. you should append string in a reverse way. else if you append 01 you will get 10 in final string
  • user541686
    user541686 over 5 years
    @AkhilSurapuram: That's what I mentioned in step #1, right?
  • Akhil Surapuram
    Akhil Surapuram over 5 years
    @Mehrdad sorry I meant to say you also need to reverse the string builder before inserting reversed strings.
  • user541686
    user541686 over 5 years
    @AkhilSurapuram: Isn't the string builder empty initially?
  • rogerdpack
    rogerdpack about 5 years
    Hmmm...the "purpose" of StringBuilder? Seems from the javadocs its "purpose" is to act as a mutable string, its "typical benefit and use" is to avoid the N^2 append loops, definitely? In this case it reintroduces an N^2 loop, but with input size of "only" 100, might still be acceptably fast to just do insert(0, )'s depending on how often, perhaps... :)
  • user541686
    user541686 about 5 years
    @rogerdpack: I'd say that's the mechanism, not the purpose. The purpose is to be asymptotically faster than string manipulation, which it won't be if you use it wrong.
  • JGFMK
    JGFMK over 4 years
    Why did this get so many likes! The class is not defined correctly - only the signature of the method call!
  • bad_coder
    bad_coder about 4 years
    Welcome to stackoverflow. Please include an explanation of what the code does and how it solves the problem in the question.