-
January 19th, 2023, 08:51 AM
#1
StringBuffer with a fixed length in Java
Which is the best way to keep a stringbuffer length constant in Java? That is, if the fixed value is 10 and the stringbuffer contains ABCDEFGHIJ, appending K will clear A, resulting in BCDEFGHIJK. I'm considering combining StringBuffer's reverse() and setLength() methods, but I'm not sure how well it will work at 100 K length.
-
January 19th, 2023, 10:25 AM
#2
Re: StringBuffer with a fixed length in Java
 Originally Posted by Nathan D
if the fixed value is 10 and the stringbuffer contains ABCDEFGHIJ, appending K will clear A, resulting in BCDEFGHIJK
This is a very particular logic, that is, inserting at the end with possible removal at the start to keep the max length. There is no such thing in the Java SE framework (certainly not in StringBuffer/StringBuilder). And I think there is nothing similar in notable libraries like the Apache Commons Lang or Google Guava (but I am not 100% sure now .. I should check the javadocs).
You can consider creating a simple class that "wraps" a StringBuffer (or StringBuilder). Something similar to this:
Code:
public class ScrollingStrBuf {
private final int maxLength;
private final StringBuffer buffer;
public ScrollingStrBuf(int maxLength) {
this.maxLength = maxLength;
buffer = new StringBuffer();
}
public ScrollingStrBuf append(CharSequence s) {
int end = s.length();
int start = end > maxLength ? end - maxLength : 0;
buffer.delete(0, Math.max(0, buffer.length() - maxLength + (end - start)));
buffer.append(s, start, end);
return this;
}
@Override
public String toString() {
return buffer.toString();
}
}
Code:
ScrollingStrBuf ssb = new ScrollingStrBuf(10);
ssb.append("ABCD"); // now ABCD
ssb.append("EF"); // now ABCDEF
ssb.append("GHIJKLM"); // now DEFGHIJKLM
ssb.append("OPQ"); // now GHIJKLMOPQ
ssb.append("RST"); // now JKLMOPQRST
This is just an idea ... it could be improved.
Last edited by andbin; January 19th, 2023 at 10:28 AM.
-
January 20th, 2023, 12:08 PM
#3
Re: StringBuffer with a fixed length in Java
SO repost bot.
https://stackoverflow.com/questions/...buffer-in-java
Multiple previous threads from this user are in a similar vein,
Most either have spam links, or have been edited to remove spam links.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|