java:使用StringBuilder在开头插入 [英] java: use StringBuilder to insert at the beginning

查看:83
本文介绍了java:使用StringBuilder在开头插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只能用字符串来做到这一点,例如:

I could only do this with String, for example:

String str="";
for(int i=0;i<100;i++){
    str=i+str;
}

有没有办法用 StringBuilder 实现这一点?谢谢.

Is there a way to achieve this with StringBuilder? Thanks.

推荐答案

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

警告: 它违背了 StringBuilder 的目的,但它可以满足您的要求.

Warning: It defeats the purpose of StringBuilder, but it does what you asked.

更好的技术(虽然仍然不理想):

  1. 反转每个要插入的字符串.
  2. 每个字符串附加到StringBuilder.
  3. 完成后反转整个 StringBuilder.
  1. Reverse each string you want to insert.
  2. Append each string to a StringBuilder.
  3. Reverse the entire StringBuilder when you're done.

这会将 O(n²) 解决方案变成 O(n).

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

这篇关于java:使用StringBuilder在开头插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆