Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Java: String and using the split function?

OK, Im trying to split a string containing an IP Address into the 4 byte address.

Here is my code:

getIP(String st){ //st contains "192.168.1.21"

String[] var = st.split(".");

...

After the split, var has a length of 0. WHY???

If I change it to:

String[] var = st.split("1");

...

I get what I would expect with var having a length of 4 and each string containing:

var[0] = ""

var[1] = "92."

var[2] = "68."

var[3] = ".2"

Can you not use the dot (.) character to split a string???

3 Answers

Relevance
  • 7 years ago
    Favorite Answer

    Split works fine, but it's expecting a regular expression. Since the "." in RegEx is a special character, you have to escape it.

    BUT since "\" has a special meaning in a string, you have to escape it TOO SO

    String[] var = st.split("\\.");

  • Anonymous
    5 years ago

    Split Function In Java

  • 7 years ago

    I've never used split (it's a while since I wrote any Java) but as it takes a regexp, you'd have to escape the . I would say.

Still have questions? Get your answers by asking now.