26

I got this simple code:

String ip = "1.2.3.4";
String[] ipArray = ip.split(".");
System.out.println(ipArray[1]);

And ipArray is null by the time it hits System.out.println (throws null pointer exception).

My question is why does ipArray stay null even though I'm setting it to split on each of ip's .s?

madth3
  • 7,275
  • 12
  • 50
  • 74
CyanPrime
  • 5,096
  • 12
  • 58
  • 79
  • You're splitting on any character, so all characters are being splitted on leaving nothing left in the array. [string.split](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)) takes a regular expression. – mellamokb Jul 12 '12 at 17:25
  • 4
    Dot `.` means "any character" :) You need a "real dot" `[.]` – Sergey Kalinichenko Jul 12 '12 at 17:25
  • To be exact, depending on the mode (DOTALL), `.` will or will not match new line character. – nhahtdh Jul 12 '12 at 17:26
  • might i add, if you were using python, you'd be pretty much 100% correct. the python split command splits by a character (or regex, but it defaults to a char) – acolyte Jul 12 '12 at 20:18
  • 3
    Just a tiny correction - this code will throw java.lang.IndexOutOfBoundsException exception, rather than NPE (as OP wrote). String#split never returns null. The issue here is that the result is an empty array. – Alex Lipov Aug 02 '15 at 14:03

4 Answers4

50

Use ip.split("\\."); and your problems will be solved. The problem is that String#split receives a regular expression, the dot (.) symbol is a special character in regular expressions, so you need to escape it for it to be interpreted as a plain dot, also as the backslash is an escape character in Java, you have to escape it too.

marko
  • 2,841
  • 31
  • 37
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
42

. is a special character in regular expressions, which is what is used to split a string.

To get around this, you need to escape the .. That leads us to \. Unfortunately, \ is ALSO a special character in the java string, so that must also be escaped, to make \\.

Our "final" result is ip.split("\\.");

In a related issue, the whole process can be averted entirely. There's no sense in doing something that a standard library already has done for us.

Consider the following

byte[] ipOctets = InetAddress.getByName(ip).getAddress();

The only issue here is to remember that if you want the int value, you have to extract it with & like int octet = ipOctets[0] & 0xFF;

corsiKa
  • 81,495
  • 25
  • 153
  • 204
5

Pattern.quote(String) can also be used to quote the whole string. This returns a pattern which will be interpreted literally, special characters will have no special meaning. This might be overkill in this case, but sometimes it can be useful.

Katona
  • 4,816
  • 23
  • 27
0

We can also use split ("[.]")

String s = "abcd.jpg";
String[] strarry = s.split ("[.]");

strarry[0]=abcd, strarry[1]=jpg

Sayak-
  • 1
  • 1