Splitter.on(‘.‘)代替split

  • Post author:
  • Post category:其他


1、传统的字符串split

【推荐】使用索引访问用String的split方法得到的数组时,需做最后一个分隔符后有无内容的检查,否则会有抛IndexOutOfBoundsException的风险。

说明:


String str = “a,b,,c,,”;


String[] ary = str.split(“,”);


// 预期大于4,结果是4

2、Splitter替代split

(1)、trimResults,从每个返回的子字符串中删除前导和尾随空格

(2)、omitEmptyStrings,从最终结果中忽略空字符串

(3)、withKeyValueSeparator转换为map

//传统的字符串split
        String strstr = "a,b,,c,,,";
        String[] ary = strstr.split(",");
        System.out.println(ary.length);
        for (int i = 0; i < ary.length; i++) {
            System.out.println(ary[i]);
        }
        System.out.println("====");
//trimResults,从每个返回的子字符串中删除前导和尾随空格
        String str = "Everyone. .  should. Learn. Data. Structures";
        List<String> myList1 = Splitter.on('.')
                .trimResults().splitToList(str);
        for (String temp:myList1) {
            System.out.println(temp);
        }
        System.out.println("====");
//omitEmptyStrings,从结果中忽略空字符串。例如,Splitter.on(',').omitEmptyStrings().split(“,a ,,, b,c ,,”)返回仅包含[“a”,“b”,“c”]
        List<String> myList2 = Splitter.on('.')
                .trimResults().omitEmptyStrings().splitToList(str);
        for (String temp:myList2) {
            System.out.println(temp);
        }
        System.out.println("====");
//withKeyValueSeparator转换为map
        Map<String, String> map1 = Splitter
                .on(",")
                .trimResults()
                .omitEmptyStrings()
                .withKeyValueSeparator("=")
                .split(EcologySwitch.insureTypeEnums);
        map1.entrySet().forEach(stringStringEntry -> {
            System.out.println(stringStringEntry.getKey()+":"+stringStringEntry.getValue());
        });
输出结果:
4
a
b

c
====
Everyone

should
Learn
Data
Structures
====
Everyone
should
Learn
Data
Structures
====
002006.flightaccident.air:16
002006.flightcompose.air:17
002006.flightisolate.air:32



版权声明:本文为xuehuagongzi000原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。