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.
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();
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.