package com.zcd.test;
import java.util.ArrayList;
import java.util.List;
public class TestJoin {
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 method5() {
List<String> list=new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
StringBuilder sBuilder=new StringBuilder();
boolean flag=false;
for(String str:list){
if(flag){
sBuilder.append(",");
}else{
flag=true;
}
sBuilder.append(str);
}
System.out.println(sBuilder.toString());
}
public static void method6() {
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 main(String[] args) {
method1();
method2();
method3();
method4();
method5();
method6();
}
}