-1

I try to split the String "1.1" to 2 new Strings:

String[] array = "1.1".split(".");
System.out.println(array[0]);

but I get a java.lang.ArrayIndexOutOfBoundsException.

Why?

Neels
  • 2,547
  • 6
  • 33
  • 40
Laren0815
  • 91
  • 1
  • 10
  • 3
    This was asked so many times. For example check out [this](http://stackoverflow.com/questions/3387622/split-string-on-as-delimiter). – WonderCsabo Apr 04 '14 at 11:39
  • Fullstop is a special character in regex. So use `"1.1".split("\\.")`. – Omoro Apr 04 '14 at 11:42
  • BTW, i suggest `"1.1".split(Pattern.quote("."))` for these cases, to improve readability. – WonderCsabo Apr 04 '14 at 11:46
  • 1
    To add something to the useful answers: In fact the split first results in 4 matches, each one being an empty string. The dot matches **any character**, so the split finds the empty string in front of the first "1", then the empty string between the "1" and the ".", and so on. But according the [method's documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)), trailing empty strings are **not included** in the resulting array. So the resulting string array itself is of length 0. – Seelenvirtuose Apr 04 '14 at 11:48

5 Answers5

6

split takes a regular expression. The dot character . is used to match any character in regular expressions so the array will be empty unless the character itself is escaped

String[] array = "1.1".split("\\.");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 2
    +1 for explaining what the dot character is used for (even though it is used here by accident) – ifloop Apr 04 '14 at 11:43
1

You need to escape dot.

String[] array = "1.1".split("\\.");
System.out.println(array[0]);

If you look into doc you'll find that split method accepts regex.

In regular expressions . mean any Character except new line.

public String[] split(String regex) {
        return split(regex, 0);
    }
Sergii Shevchyk
  • 38,716
  • 12
  • 50
  • 61
1

You need to escape the . with \\ so that it is not taken as a regex meta character as split takes a regular expression. You may try like this:

String[] array = "1.1".split("\\.");
System.out.println(array[0]);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

try String[] array = "1.1".split("\\.");

zapdroid
  • 562
  • 5
  • 16
1

you have to use "1.1".split("\\.")

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56