Java String split removed empty values

前端 未结 5 1315
无人及你
无人及你 2020-11-21 18:41

I am trying to split the Value using a separator. But I am finding the surprising results

String data = \"5|6|7||8|9||\";
String[] split = data.split(\"\\\\|         


        
5条回答
  •  执笔经年
    2020-11-21 19:20

    String[] split = data.split("\\|",-1);

    This is not the actual requirement in all the time. The Drawback of above is show below:

    Scenerio 1:
    When all data are present:
        String data = "5|6|7||8|9|10|";
        String[] split = data.split("\\|");
        String[] splt = data.split("\\|",-1);
        System.out.println(split.length); //output: 7
        System.out.println(splt.length); //output: 8
    

    When data is missing:

    Scenerio 2: Data Missing
        String data = "5|6|7||8|||";
        String[] split = data.split("\\|");
        String[] splt = data.split("\\|",-1);
        System.out.println(split.length); //output: 5
        System.out.println(splt.length); //output: 8
    

    Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.

        String data = "5|6|7||8|||";
        String[] split = data.split("\\|");
        String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
        System.out.println(split.length); //output: 5
        System.out.println(splt.length); //output:7
    

    What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.

提交回复
热议问题