Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 993
Lina Avatar asked Dec 05 '22 18:12

Lina


2 Answers

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.

like image 60
Andreas Fester Avatar answered Dec 09 '22 13:12

Andreas Fester


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.

like image 30
Andy Turner Avatar answered Dec 09 '22 15:12

Andy Turner