简体   繁体   English

如何在Java中将IP字符串转换为整数数组?

[英]How to convert an IP string to an array of integers in java?

I'm trying to make an array of integers from an IP string in java. 我正在尝试从Java中的IP字符串制作一个整数数组。 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 "." 我知道parseInt工具,但是如何使用“。”。 ?

Sorry the noob question, I'm still a beginner. 抱歉,菜鸟问题,我仍然是初学者。

Split your string by . 用分割字符串. sign. 标志。 Solution using Java 8 Streams : 使用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. Integer::parseInt ,因为它返回原始的也许是更好地在这里int而不是IntegerInteger::valueOf一样。 So to avoid unnecessary unboxing : 因此,为了避免不必要的拆箱:

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

You can use the String.split() method. 您可以使用String.split()方法。

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 . Java Regex Engine中的特殊字符。 Otherwise if the string was split with brackets, then str.split("-") would be sufficient. 否则,如果使用括号将字符串分割开,则str.split("-")就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM