0

When I try this code in a new project, I have this error:

java.lang.ArrayIndexOutOfBoundsException: 0 at line 4

String temp = "Capture.png";
System.out.println(temp);
String[] temp2 = temp.split(".");
System.out.println(temp2[0]);

The main action is to verify the extension of the file but when I'm trying this, the split function doesn't work.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
FuxTheFox
  • 99
  • 1
  • 9
  • Java uses a regex for the split argument. – Robert Harvey Jul 10 '14 at 16:10
  • `.split()` needs a regular expression, not just a character or another string. – takendarkk Jul 10 '14 at 16:11
  • @Takendarkk: Why does [this](http://stackoverflow.com/a/3481842/102937) work? Does the period need to be escaped? – Robert Harvey Jul 10 '14 at 16:11
  • @RobertHarvey No clue :) I just assume the OP is thinking that the String will be split around the period which is not what is going to actually happen. – takendarkk Jul 10 '14 at 16:14
  • "For other readers finding this answer it should be remarked that escaping special regex characters is done with backslashes, e.g. split("\\.") which look in the answer like vertical bars due to the italics font" One of the comments in that link you just sent. :D – Shrey Jul 10 '14 at 16:15

3 Answers3

3

Java uses a regex for the split argument, and a period means something in regex.

Try escaping the period.

String temp = "Capture.png";
System.out.println(temp);
String[] temp2 = temp.split("\\.");
System.out.println(temp2[0]);
devnull
  • 118,548
  • 33
  • 236
  • 227
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
3

You need to escape the period, i.e., it must be temp.split("\\.").

Otherwise, it will treat period as "any character". Since any character matches all characters of your string, your complete string becomes only separators. Since separators are left out of the split result, the split result is empty. This is why you get the out of bounds exception.

gexicide
  • 38,535
  • 21
  • 92
  • 152
1

Java uses a regular expression as argument for the method split as stated on the docs here

A . is a character that represents all characters in a regular expression. So you need to escape it on your code, like this:

String temp = "Capture.png";
System.out.println(temp);
String[] temp2 = temp.split("\\.");
System.out.println(temp2[0]);

Note that It is escaped with two \ because \ also is a control character in a regular expression so, it needs to be escaped as well.

Jorge Campos
  • 22,647
  • 7
  • 56
  • 87