简体   繁体   English

如何删除java中字符串缓冲区的最后一个字符?

[英]How to remove last character of string buffer in java?

I have following code, I wanted to remove last appended character from StringBuffer : 我有以下代码,我想删除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) 我想删除最后一个值后的“,”(完成For循环后)

For your concrete use case, consider the answer from @AndyTurner. 对于您的具体用例,请考虑@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? 如何删除java中字符串缓冲区的最后一个字符?

you can simply adjust the length of the StringBuffer with StringBuffer.setLength() : 你可以使用StringBuffer.setLength()简单地调整StringBuffer的长度:

...
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 . 请注意,这要求StringBuffer中至少有一个字符可用,否则您将获得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. 如果给定长度小于当前长度,则setLength方法实质上将AbstractStringBuilder类的count成员设置为给定的新长度。 No other operations like character array copies are executed in that case. 在这种情况下,不会执行其他操作,如字符数组副本。

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 . 另请注意,如果您不需要同步(此代码中没有显示),则最好使用StringBuilder

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);

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(",");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM