Java拼接字符串时 去掉最后一个多余的逗号
分享一下我老师大神的人工智能教程!零基础,通俗易懂!
当我们遍历拼接字符串的时候,最后会多出一个我们添加的字符(比如逗号)
可使用如下三种方法去掉最后多余的符号
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));} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15当我们遍历拼接字符串的时候,最后会多出一个我们添加的字符(比如逗号) 可使用如下三种方法去掉最后多余的符号 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));} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
给我老师的人工智能教程打call!
下一篇:
【第三周】基本数据类型