标签:
import java.lang.StringBuilder;
public class Stringadd {
public static void method1() {
String[] name = { "嘿嘿", "嘻", "等等等" };
StringBuffer sb = new StringBuffer();
for (int i = 0; i < name.length; i++) {// 第一个直接打印
if (i > 0) {// name[0]打印完了后 加逗号; 直到name 数组的倒数第2个
sb.append(",");
}
sb.append(name[i]);// 加上name 数组的最后一个元素;
}
System.out.println(sb.toString());
}
public static void method2() {
String[] name = { "嘿嘿", "嘻", "等等等" };
String d = "";
for (int i = 0; i < name.length; i++) {
if (i == name.length - 1) {// 最后一个元素不加逗号,其他的元素后加
d += name[i];
} else {
d += name[i] + ",";
}
}
System.out.println(d);
}
public static void method3() {
String str = "嘿嘿,嘻,等等等,";
str = str.substring(0, str.length() - 1);
System.out.println(str);
}
public static void method4() {
// 1 使用StringBuilder 进行操作,节省内存
// 2 使用deleteCharAt 删除最后的逗号
String[] name = { "嘿嘿", "嘻", "等等等" };
StringBuilder b = new StringBuilder();
for (int i = 0; i < name.length; i++) {
b.append(name[i]);
b.append(",");
}
if (b.length() > 0) {
b.deleteCharAt(b.length() - 1);
}
System.out.println(b.toString());
}
public static void main(String args[]) {
Stringadd.method1();
Stringadd.method2();
Stringadd.method3();
Stringadd.method4();
}
}
标签:
原文地址:http://my.oschina.net/u/2358326/blog/420884