4

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)

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
Lina
  • 305
  • 1
  • 6
  • 15

4 Answers4

11

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.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
4

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Try this code:

Added below line to your existing code.

 Ser = Ser.substring(0, Ser.length()-1); 

Complet code:

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();
    Ser = Ser.substring(0, Ser.length()-1);
fieldSerNo.setText(Ser);
mattyman
  • 351
  • 2
  • 16
0

Pls check this .

Why u want to remove the last appended character , do not append then ? if you are not using the character for further .

    for (int i = 0; i < MMqty-1;i++){
        Att.append(m_masi.getSerNo(true)).append(",");
    }
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
Chandu
  • 11
  • 1
  • 2