3

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!

1
  • . means any character in a regular expression. Commented Aug 15, 2012 at 12:11

2 Answers 2

8
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)

Sign up to request clarification or add additional context in comments.

1 Comment

To explain a bit further: The first parameter to split is a regex. "\\." in a string literal becomes \. in memory. And \. in a regex matches a literal .
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.