[英]How to extract the first three segments of an IP address in android
例:
xxx.xxx.xxx.xxx是IP地址格式,我只想获取前三个段(带点):xxx.xxx.xxx。
另一个例子:
192.168.0.160,我只需要192.168.0。
String[] splittedArray = ipAddressString.split("\\.");
String firstThreeSegments = splittedArray [0] + "." + splittedArray [1] + "." + splittedArray [2] + ".";
String partialIp = ipAddress.substring(0, ipAddress.lastIndexOf(".")+1);
您可以使用String#replaceFirst
String firstThree = ip.replaceFirst("\\d+$", "");
这将替换任何有效IP地址的最后一部分,并用空字符串替换。
我想说的最简单的方法(IMO)是使用(来自Apache Commons) StringUtils.ordinalIndexOf()
查找第三个时间段的索引值,然后使用substring()
将子字符串从0转换为该索引值。
例如:
StringUtils.ordinalIndexOf("192.168.0.160", ".", 3) == 9
然后,您可以使用此索引获取子字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.