拼接字符串时去掉最后一个多余逗号


当我们遍历拼接字符串的时候,最后会多出一个我们添加的字符(比如逗号)。

方式一:

String str[] = { "hello", "beijing", "world", "shenzhen" };
StringBuffer buf = new StringBuffer();

for (int i = 0; i < str.length; i++) {
    buf.append(str[i]).append(",");
}

if (buf.length() > 0) {
    //方法一  : substring
    System.out.println(buf.substring(0, buf.length()-1));
    //方法二 :replace
    System.out.println(buf.replace(buf.length() - 1, buf.length(), ""));
    //方法三: deleteCharAt
    System.out.println(buf.deleteCharAt(buf.length()-1));
}

  

方式二:

StringBuilder sdb = new StringBuilder();
for ( int t = 0; t < memberLen; t++ )
{
    memTemp = stafferMap.get( strMember[t] );
    if ( memTemp != null )
    {
        if ( sbd.length > 0 )
        {
            sbd.append( "," ).append( memTemp );
        }else{
            sbd.append( memTemp );
        }
    }
}

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM