当我们遍历拼接字符串的时候,最后会多出一个我们添加的字符(比如逗号)。
方式一:
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 ); } } }
原文地址:https://www.cnblogs.com/panchanggui/p/9847838.html
时间: 2024-10-10 09:30:05