You can use delete :
void append(String s) { buffer.append(s); if(buffer.length() > MAX_LENGTH){ buffer.delete(0, buffer.length() - MAX_LENGTH); } }
Update . If the parameter is a long string, this results in unnecessary selection of StringBuffer. To avoid this, you can first reduce the buffer and then add only as many line characters as necessary:
void append(String s) { if (buffer.length() + s.length() > MAX_LENGTH) { buffer.delete(0, buffer.length() + s.length() - MAX_LENGTH); } buffer.append(s, Math.max(0, s.length() - MAX_LENGTH), s.length()); }
Kapep source share