0

I'm having a problem with the split function returning a blank array. When any index is called from the array, it throws an index out of bounds exception. Here is the code:

class splitNumber {
    public static void main(String[] args) {
        String number = "3.84";
        String[] sep = number.split(".");
        System.out.println(sep[0]);
    }
}

Is there any fix or workaround for this? I'm using Java SE 7.

3 Answers3

1

As noted elsewhere, String#split takes a regex. One alternate way to construct that regex is to use Pattern#quote:

String number = "3.84";
String[] sep = number.split(Pattern.quote("."));
System.out.println(Arrays.toString(sep));

This saves you from typing a bunch of tedious escape chars.

The111
  • 5,757
  • 4
  • 39
  • 55
0

"." is a special character in regex and String's split method accepts regex, which you need to escape like:

String[] sep = number.split("\\.");
SMA
  • 36,381
  • 8
  • 49
  • 73
0

Use "\."

"Note that this takes a regular expression, so remember to escape special characters if necessary, e.g. if you want to split on period . which means "any character" in regex, use either split("\.") or split(Pattern.quote("."))."

How to split a string in Java

Community
  • 1
  • 1