java:使用StringBuilder在开头插入 [英] java: use StringBuilder to insert at the beginning
本文介绍了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.
更好的技术(虽然仍然不理想):
- 反转每个要插入的字符串.
- 将每个字符串附加到
StringBuilder
. - 完成后反转整个
StringBuilder
.
- Reverse each string you want to insert.
- Append each string to a
StringBuilder
. - 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屋!
查看全文