3
public class test {
    public static void main(String[] args) {        
        String[] arr = {"0 1.2.3.4","a b.c.d.e"};
        System.out.println(arr[0].split(".")[2]);
    }
}

I am using java 8.

the expected output is 3.

TheFox
  • 79
  • 8

1 Answers1

7

The argument to split is a regular expression, not a literal 'this is the string you should scan for'. The . symbol in regex means 'anything', so it's like " ".split(" ") - the string you're passing is all separators, hence, you get no output.

.split(Pattern.quote(".")) will take care of it.

EDIT: To go in some detail - given that the string consists of all separators, split initially provides you with an array filled with empty strings; one for each position 'in between' any character (as each character is a separator). However, by default split will strip all empty strings off of the end, hence you end up with a 0-length string array.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • 3
    (alternatively, you can also escape it manually `"\\."`) – Zabuzard Mar 02 '22 at 12:58
  • "the string you're passing is all separators, hence, you get no output" you should perhaps explain that empty tokens are stripped from the end, unless you pass a negative limit. – Andy Turner Mar 02 '22 at 14:00
  • Edited to add that detail; didn't bother with the negative number trick: OP is not trying to make those empty strings appear. They just want to know why `.split(".")` doesn't split on dots. – rzwitserloot Mar 03 '22 at 00:56