需要注意的点:
xi
是一个 十六进制字符串 ,可以包含数字、小写英文字母('a'
到'f'
)和大写英文字母('A'
到'F'
)。
这个条件可以根据ASCii码写成:
if(c<'0'||c>'9'&&c<'A'||c>'F'&&c<'a'||c>'f'){
return false;
}
因为ASCii码如下:
public String validIPAddress(String queryIP) {
if(queryIP.indexOf('.')>0){
return isIPv4(queryIP)?"IPv4":"Neither";
}
else {
return isIPv6(queryIP)?"IPv6":"Neither";
}
}
private boolean isIPv4(String queryIP) {
String[] arr = queryIP.split("\\.",-1);
int len = arr.length;
if(len!=4) return false;
for (int i = 0; i < len; i++) {
String temp = arr[i];
if(temp.length()==0||temp.length()>3) return false;
if (temp.length() > 1 && temp.charAt(0) == '0') {
return false;
}
for (int k = 0; k < temp.length(); k++) {
char c = temp.charAt(k);
if (!Character.isDigit(c)) {
return false;
}
}
int number = Integer.parseInt(temp);
if (number < 0 || number > 255) {
return false;
}
}
return true;
}
private boolean isIPv6(String queryIP){
String[] arr = queryIP.split(":",-1);
int len = arr.length;
if(len!=8) return false;
for(int i=0;i<len;i++){
String temp=arr[i];
if(temp.length()<1||temp.length()>4){
return false;
}
for(int k=0;k<temp.length();k++){
char c=temp.charAt(k);
if(c<'0'||c>'9'&&c<'A'||c>'F'&&c<'a'||c>'f'){
return false;
}
}
}
return true;
}