java: use StringBuilder to insert at the beginning

前端 未结 9 1931
佛祖请我去吃肉
佛祖请我去吃肉 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:24

    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));
            }
        }
    }
    

提交回复
热议问题