자바 : StringBuilder를 사용하여 처음에 삽입
예를 들어 다음과 같이 String으로 만이 작업을 수행 할 수 있습니다.
String str="";
for(int i=0;i<100;i++){
str=i+str;
}
StringBuilder로 이것을 달성하는 방법이 있습니까? 감사.
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
경고 : 의 목적에 위배StringBuilder
되지만 요청한대로 수행됩니다.
더 나은 기술 (아직 이상적이지는 않지만) :
- 역 각각 삽입 할 문자열입니다.
- 추가 A와 각 문자열을
StringBuilder
. - 역 전체를
StringBuilder
작업을 완료 할 때.
이것은 O ( n ²) 솔루션을 O ( n ) 으로 바꿉니다 .
당신이 사용할 수있는 strbuilder.insert(0,i);
아마도 내가 뭔가를 놓치고 있지만 다음과 같은 문자열로 마무리하고 싶 "999897969594...543210"
습니까?
StringBuilder sb = new StringBuilder();
for(int i=99;i>=0;i--){
sb.append(String.valueOf(i));
}
대체 솔루션으로 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();
이 스레드는 꽤 오래되었지만 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));
}
}
}
I had a similar requirement when I stumbled on this post. I wanted a fast way to build a String that can grow from both sides ie. add new letters on the front as well as back arbitrarily. I know this is an old post, but it inspired me to try out a few ways to create strings and I thought I'd share my findings. I am also using some Java 8 constructs in this, which could have optimised the speed in cases 4 and 5.
https://gist.github.com/SidWagz/e41e836dec65ff24f78afdf8669e6420
The Gist above has the detailed code that anyone can run. I took few ways of growing strings in this; 1) Append to StringBuilder, 2) Insert to front of StringBuilder as as shown by @Mehrdad, 3) Partially insert from front as well as end of the StringBuilder, 4) Using a list to append from end, 5) Using a Deque to append from the front.
// 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(""));
I'll focus on the front append only cases ie. case 2 and case 5. The implementation of StringBuilder internally decides how the internal buffer grows, which apart from moving all buffer left to right in case of front appending limits the speed. While time taken when inserting directly to the front of the StringBuilder grows to really high values, as shown by @Mehrdad, if the need is to only have strings of length less than 90k characters (which is still a lot), the front insert will build a String in the same time as it would take to build a String of the same length by appending at the end. What I am saying is that time time penalty indeed kicks and is huge, but only when you have to build really huge strings. One could use a deque and join the strings at the end as shown in my example. But StringBuilder is a bit more intuitive to read and code, and the penalty would not matter for smaller strings.
Actually the performance for case 2 is much faster than case 1, which I don't seem to understand. I assume the growth for the internal buffer in StringBuilder would be the same in case of front append and back append. I even set the minimum heap to a very large amount to avoid delay in heap growth, if that would have played a role. Maybe someone who has a better understanding can comment below.
참고URL : https://stackoverflow.com/questions/5931261/java-use-stringbuilder-to-insert-at-the-beginning
'Programing' 카테고리의 다른 글
kubernetes 서비스 외부 IP 보류 중 (0) | 2020.10.09 |
---|---|
Looper.prepare ()를 호출하지 않은 스레드 내부에 핸들러를 만들 수 없습니다. (0) | 2020.10.09 |
성능 저하없이 UITableView의 원형 UIImageView? (0) | 2020.10.09 |
Xcode 5-DVTPlugInCompatibilityUUID에 필요한 플러그인이 없습니까? (0) | 2020.10.09 |
Git Bash : 인증 에이전트에 대한 연결을 열 수 없습니다. (0) | 2020.10.09 |