How to remove last character of string buffer in java?

Lina picture Lina · May 3, 2016 · Viewed 11.4k times · Source

I have following code, I wanted to remove last appended character from StringBuffer:

StringBuffer Att = new StringBuffer();
BigDecimal qty = m_line.getMovementQty();
int MMqty = qty.intValue();
for (int i = 0; i < MMqty;i++){
    Att.append(m_masi.getSerNo(true)).append(",");
}
String Ser= Att.toString();
fieldSerNo.setText(Ser);

I want to remove " , " after last value come (After finishing the For loop)

Answer

Andreas Fester picture Andreas Fester · May 3, 2016

For your concrete use case, consider the answer from @AndyTurner. Not processing data which will be discarded later on is, in most cases, the most efficient solution.

Otherwise, to answer your question,

How to remove last character of string buffer in java?

you can simply adjust the length of the StringBuffer with StringBuffer.setLength():

...
StringBuffer buf = new StringBuffer();
buf.append("Hello World");
buf.setLength(buf.length() - 1);
System.err.println(buf);
...

Output:

Hello Worl

Note that this requires that at least one character is available in the StringBuffer, otherwise you will get a StringIndexOutOfBoundsException.

If the given length is less than the current length, the setLength method essentially sets the count member of the AbstractStringBuilder class to the given new length. No other operations like character array copies are executed in that case.