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?
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?
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("\\.");
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);
}
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]);