How to remove last character of string buffer in java?

12,300

Solution 1

Don't append it in the first place:

for (int i = 0; i < MMqty;i++){
    Att.append(m_masi.getSerNo(true));
    if (i + 1 < MMqty) Att.append(",");
}

Also, note that if you don't require the synchronization (which you don't appear to in this code), it may be better to use StringBuilder.

Solution 2

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.

Share:
12,300
Lina
Author by

Lina

Updated on July 03, 2022

Comments

  • Lina
    Lina almost 2 years

    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)