USEGEAR

导航

java学习-6-核心类:字符串StringJoiner 和数组一起玩

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

posted on 2021-12-30 12:26  USEGEAR  阅读(77)  评论(0编辑  收藏  举报