Search code examples
javastringstringbuffer

How to remove last character of string buffer in java?


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)


Solution

  • 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.