I'm embarrassed to ask this one, it's a real newbie question but it's been kicking my butt all morning. Here goes: I'm trying to split an IP address up into four seperate strings using the three periods as delimiters. Here's the code I am using:
Toast.makeText(getBaseContext(),s,Toast.LENGTH_SHORT).show();
String[] ip = s.split(".",4);
String ip0ne = ip[0];
String ipTwo = ip[1];
String ipThree = ip[2];
String ipFour = ip[3];
's' is the string containing the ip address '82.163.99.82', this is verified in the toast The problem is, ipOne, ipTwo and ipThree end up containing nothing, and ipFour ends up containing '163.99.82' The first number of the ip address has disappeared altogether. Help please!
String[] ip = s.split("\\.",4);
The string argument is evaluated as a regular expression and so we have to escape the dot (and in java we have to escape the escape-char too - therefore: a double-backslash)
The split method takes a regular expression - and . in a regular expression matches any character :( Personally I think it's crazy for any non-regex API to take a regex as a String without having anything in the method name to indicate that, but hey...
You could use "\\." as the split value - but I would personally use Guava and its Splitter type:
private static final Splitter DOT_SPLITTER = Splitter.on('.').limit(4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With