128

Check out the below program.

try {
    for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){
        String[] de = data.split(";");
        System.out.println("Length = " + de.length);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Sample.txt:

1;2;3;4
A;B;;
a;b;c;

Output:

Length = 4
Length = 2
Length = 3

Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws ArrayIndexOutOfBoundsException)?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
raja
  • 4,043
  • 6
  • 30
  • 24

2 Answers2

311

You can specify to apply the pattern as often as possible with:

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

See the Javadoc for the split method taking two arguments for details.

Brian McKenna
  • 45,528
  • 6
  • 61
  • 60
Fabian Steeg
  • 44,988
  • 7
  • 85
  • 112
  • Should not the parameter be zero, as demonstrated by the last two examples of the Javadoc? – Nicolas Raoul Apr 05 '17 at 07:48
  • Why does a String containing empty space character as last character gets returned when delimitter is an empty space character " " ? Eg: `String s = "a "; public static int lengthOfLastWord(String s) { int l = 0; for(String eachWord : s.split("\\s+", -1)){ if(!eachWord.equals(" ")){ l = eachWord.length(); System.out.println("'" + eachWord + "'"); } } return l; }` returns 'a' and ' '. Whereas, if `String s = "a a";` then output is just 'a' followed by another 'a' Why is this happening in Java 8? – sofs1 Feb 01 '19 at 23:06
27

have a look at the docs, here the important quote:

[...] the array can have any length, and trailing empty strings will be discarded.

If you don't like that, have a look at Fabian's comment. When calling String.split(String), it calls String.split(String, 0) and that discards trailing empty strings (as the docs say it), when calling String.split(String, n) with n < 0 it won't discard anything.

Johannes Weiss
  • 52,533
  • 16
  • 102
  • 136