1

I'm trying to make an array of integers from an IP string in java. For example:

String ip = "192.168.0.1";
int[] ipArray = new int[4];
int[0] = 192; int[1] = 168; int[2] = 0; int[3] = 1;

any idea how can I do this?

I know the parseInt tool, but how can I work with the "." ?

Sorry the noob question, I'm still a beginner.

2
  • Split the string with . (dot) and then apply parseInt Commented May 20, 2019 at 19:18
  • 1
    int[] ipArray = Arrays.stream(ip.split("\\.")).mapToInt(Integer::parseInt).toArray(); Commented May 20, 2019 at 19:20

2 Answers 2

2

Split your string by . sign. Solution using Java 8 Streams :

int[] ipArray = Arrays.stream(ip.split("\\."))
                .mapToInt(Integer::valueOf)
                .toArray();

EDIT

Integer::parseInt might be better here as it returns primitive int instead of Integer like Integer::valueOf does. So to avoid unnecessary unboxing :

int[] ipArray = Arrays.stream(ip.split("\\."))
                .mapToInt(Integer::parseInt)
                .toArray();
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the String.split() method.

For example:

String str = "192.168.0.1";
String[] strSplit = str.split("\\.");
int[] intArray = new int[strSplit.length];
for(int i=0; i<intArray.length; i++){
    intArray[i] = Integer.parseInt(strSplit[i]);
}

The reason for \\. is because . is a special character in Java Regex Engine. Otherwise if the string was split with brackets, then str.split("-") would be sufficient.

1 Comment

Thanks for the help!

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.