For some reason, I can get the split method to work. I honestly have no idea what I’m doing wrong this this code:
String address = "0.0.0.0";
String [] adr = address.split(".");
System.out.println(address);
System.out.println(adr[0]);
I’m getting an index out of bounds error on the array accessor. Any ideas as to where I’ve gone wrong?
The
split()method expects a regular-expression, not a literal string, and the “.” character has a special meaning in regular expressions. To split on a literal “.” character, you need to escape it so that the regex parser understands that’s what you want.Try it like this:
Note that it is necessary to essentially escape it twice, because you want the regex parser to get the string “\.”, which is actually “\\.” when expressed as a string literal. The “\\” resolves to a literal “\” character, so the regex parser is given “\.”, which it then resolves to a literal “.” character.
Also note that the stackoverflow parser appears to want to unescape certain sequences beginning with a “\”, making this post confusing to edit.