java: use StringBuilder to insert at the beginning

前端 未结 9 1935
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 03:55

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 wit

相关标签:
9条回答
  • 2021-01-30 04:26

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

    0 讨论(0)
  • 2021-01-30 04:30

    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();
    
    0 讨论(0)
  • 2021-01-30 04:33

    You can use the insert method with the offset. as offset set to '0' means you are appending to the front of your StringBuilder.

    StringBuilder sb = new StringBuilder();
    for(int i=0;i<100;i++){
        sb.insert(0,i);
    }
    

    NOTE: as the insert method accept all types of primitives, you can use for int, long, char[] etc.

    0 讨论(0)
提交回复
热议问题