7

Possible Duplicate:
The split() method in Java does not work on a dot (.)

I'm new to java. I want to split a String from "." (dot) and get those names one by one. But this program gives error: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0" please help me

 String input1 = "van.bus.car";

 System.out.println(input.split(".")[0]+"");

 System.out.println(input.split(".")[1]+"");

 System.out.println(input.split(".")[2]+"");
Community
  • 1
  • 1
heshan
  • 115
  • 1
  • 4
  • 8
  • 1
    it is probably worth keeping the string array returned from your split call, and maybe add a test or read the values from the array in a loop to ensure that you are not trying to get a value that does not exist in your array – John Kane Oct 15 '12 at 18:11

2 Answers2

21

In regex, Dot(.) is a special meta-character which matches everything.

Since String.split works on Regex, so you need to escape it with backslash if you want to match a dot.

System.out.println(input.split("\\.")[0]+"");

To learn more about Regex, refer to following sites: -

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
7

The argument to split is a regex, and so the full stop/dot/. has a special meaning: match any character. To use it literally in your split, you'll need to escape it:

String[] splits = input1.split("\\.");

That should give you an array of length 3 for your input string.

For more about regex and which characters are special, see the docs for Pattern.

pb2q
  • 58,613
  • 19
  • 146
  • 147