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

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

问题描述

我只能使用String进行此操作,例如:

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.

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

Better technique (although still not ideal):


  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天全站免登陆