Splitting String in Java with empty elements

后端 未结 3 1188
后悔当初
后悔当初 2021-01-27 12:16

I\'m reading from a .csv File line by line. One line could look for example as following: String str = \"10,1,,,,\".

Now I would like to split according to

相关标签:
3条回答
  • 2021-01-27 12:34

    You need to use it with -1 parameter

    String[] splitted = str.split(",", -1);
    

    This has been discussed before, e.g. Java: String split(): I want it to include the empty strings at the end

    But split really shouldn't be the way you parse a csv, you could run into problems when you have a String value containing a comma

    23,"test,test","123.88"
    

    split would split the row into 4 parts:

    [23, "test, test", "123.88"]
    

    and I don't think you want that.

    0 讨论(0)
  • 2021-01-27 12:40

    Pass -1 (or any negative number, actually) as a second parameter to split:

    System.out.println("0,,,,,".split(",", -1).length); // Prints 6.
    
    0 讨论(0)
  • 2021-01-27 12:48

    split only drops trailing delimeters by default. You can turn this off with

    String str = "9,,,1,,";
    String[] parts = str.split(",", -1);
    System.out.println(Arrays.toString(parts));
    

    prints

    [9, , , 1, , ]
    
    0 讨论(0)
提交回复
热议问题