我只能用String执行此操作,例如:
String str="";
for(int i=0;i<100;i++){
str=i+str;
}
有没有办法用StringBuilder实现这个目的?感谢。
答案 0 :(得分:157)
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
警告: 它违背了StringBuilder
的目的,但它完成了您的要求。
更好的技术(虽然仍然不理想):
StringBuilder
。StringBuilder
。这会将O( n ²)解决方案变为O( n )。
答案 1 :(得分:26)
您可以使用strbuilder.insert(0,i);
答案 2 :(得分:11)
也许我错过了一些东西,但是你想找到一个看起来像这样的字符串,"999897969594...543210"
,对吗?
StringBuilder sb = new StringBuilder();
for(int i=99;i>=0;i--){
sb.append(String.valueOf(i));
}
答案 3 :(得分:6)
作为替代解决方案,您可以使用LIFO结构(如堆栈)来存储所有字符串,并在完成后将它们全部取出并将它们放入StringBuilder中。它会自然地反转放置在其中的项目(字符串)的顺序。
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();
答案 4 :(得分:4)
这个线程很老了,但你也可以想一下递归StringBuilder的递归解决方案。这允许防止任何反向处理等。只需要通过递归设计迭代并仔细决定退出条件。
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));
}
}
}
答案 5 :(得分:2)
https://gist.github.com/SidWagz/e41e836dec65ff24f78afdf8669e6420
上面的要点有详细的代码,任何人都可以运行。 我在这方面采取了几种方法来增长; 1)附加到StringBuilder,2)插入StringBuilder的前面,如@Mehrdad所示,3)从StringBuilder的前面和末尾部分插入,4)使用列表从末尾追加,5)使用Deque来从前面追加。
// Case 2
StringBuilder build3 = new StringBuilder();
IntStream.range(0, MAX_STR)
.sequential()
.forEach(i -> {
if (i%2 == 0) build3.append(Integer.toString(i)); else build3.insert(0, Integer.toString(i));
});
String build3Out = build3.toString();
//Case 5
Deque<String> deque = new ArrayDeque<>();
IntStream.range(0, MAX_STR)
.sequential()
.forEach(i -> {
if (i%2 == 0) deque.addLast(Integer.toString(i)); else deque.addFirst(Integer.toString(i));
});
String dequeOut = deque.stream().collect(Collectors.joining(""));
我将专注于前面附加的情况,即。情况2和案例5. StringBuilder的实现在内部决定内部缓冲区如何增长,除了在前端附加限制速度的情况下从左到右移动所有缓冲区。直接插入StringBuilder前面所花费的时间增长到非常高的值,如@Mehrdad所示,如果需要只有长度小于90k字符的字符串(仍然很多),前插入将构建一个String,同时通过在末尾附加来构建相同长度的String。我所说的是时间惩罚确实会被踢出并且是巨大的,但只有当你必须构建非常庞大的字符串时。可以使用双端队列并在末尾连接字符串,如我的示例所示。但是StringBuilder的读取和编码更直观,对于较小的字符串,惩罚也无关紧要。
实际上案例2的表现要比案例1快得多,我似乎并不理解。我假设StringBuilder中内部缓冲区的增长在前加法和后加法的情况下是相同的。我甚至将最小堆设置为非常大的数量,以避免延迟堆增长,如果这会起到作用。也许有更好理解的人可以在下面发表评论。
答案 6 :(得分:1)
Difference Between String, StringBuilder And StringBuffer Classes
String
String is immutable ( once created can not be changed )object. The object created as a
String is stored in the Constant String Pool.
Every immutable object in Java is thread-safe, which implies String is also thread-safe. String
can not be used by two threads simultaneously.
String once assigned can not be changed.
StringBuffer
StringBuffer is mutable means one can change the value of the object. The object created
through StringBuffer is stored in the heap. StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this, it does not allow two threads to simultaneously access the same method. Each
method can be accessed by one thread at a time.
But being thread-safe has disadvantages too as the performance of the StringBuffer hits due
to thread-safe property. Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
String Buffer can be converted to the string by using
toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed.
/
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is the same as the StringBuffer, that is it stores the object in heap and it can also
be modified. The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread-safe.
StringBuilder is fast as it is not thread-safe.
/
// The above object is stored in the heap and its value can be modified
/
// Above statement is right as it modifies the value which is allowed in the StringBuilder
答案 7 :(得分:1)
您可以使用带有偏移量的insert方法。 如果将offset设置为'0',则意味着您将追加到StringBuilder的前端。
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0,i);
}
注意: 由于insert方法接受所有类型的基元,因此可以用于int,long,char []等。
答案 8 :(得分:0)
怎么样:
StringBuilder builder = new StringBuilder();
for(int i=99;i>=0;i--){
builder.append(Integer.toString(i));
}
builder.toString();
OR
StringBuilder builder = new StringBuilder();
for(int i=0;i<100;i++){
builder.insert(0, Integer.toString(i));
}
builder.toString();
但是,与此同时,您正在执行操作O(N ^ 2)而不是O(N)。
java文档的摘录:
将Object参数的字符串表示形式插入其中 字符序列。总体效果就像第二 方法将参数转换为字符串
String.valueOf(Object)
,然后该字符串的字符 以指定的偏移量插入到此字符序列中。