public class Main { public static void main(String[] args) { String[] names = {"Bob", "Alice", "Grace"}; var sj = new StringJoiner("-"); for (String name : names) { sj.add(name); } System.out.println(sj.toString()); } }
Bob-Alice-Grace
这个对于json是非常有用的。后面我们大量和json一起玩,所以这个玩意要熟练掌握。
//需要串头和串尾的话 public class Main { public static void main(String[] args) { String[] names = {"Bob", "Alice", "Grace"}; var sj = new StringJoiner(", ", "Hello ", "!"); for (String name : names) { sj.add(name); } System.out.println(sj.toString()); } }
Hello Bob, Alice, Grace!
String.join()静态方法更好用 String[] names = {"Bob", "Alice", "Grace"}; var s = String.join(", ", names);
感谢廖老师的课程 https://www.liaoxuefeng.com/wiki/1252599548343744/1271993169413952