日期:2014-05-19  浏览次数:20991 次

字符串匹配问题??
String ip = "192.16.0.4";
 String ip2 = "192.168.0.1;192.168.1.9";

怎么判断ip是否在ip2之间???

------解决方案--------------------
这不是字符比了吧
这是ip比较,
这种写个方法,截取每个数,比较。
找一下,或许有实现的。
------解决方案--------------------
转成long型来判断就可以
比如 192.16.0.4转成192168000004
192.168.0.1转成192168000001 192.168.1.9转成192168001009
所以 192168000001 <= 192168000004 <= 192168001009

String ip = "192.168.0.4";
String[] sa = ip.split(".");
long l1 = 0;
for (String s : sa) {
l1 = l1 * 1000 + Integer.valueOf(s).intValue();
}
String ip2 = "192.168.0.1;192.168.1.9";
sa = ip2.split(";");
long l2=0, l3=0;
for (String s : sa[0].split(".")) {
l2 = l2 * 1000 + Integer.valueOf(s).intValue();
}
for (String s : sa[1].split(".")) {
l3 = l3 * 1000 + Integer.valueOf(s).intValue();
}
if (l1 <= l2 && l2 <= l3) {
...
}



------解决方案--------------------
Java code

public class CibTest 
{
    public static void main(String[] args) 
    {
        String loc_ip = "192.16.1.8";
        boolean loc_result = new CibTest().isAddressInclude(loc_ip);
        System.out.println(loc_result);
    }
    
    private boolean isAddressInclude(String ip_ipAddr)
    {
         try
         {
             String loc_ip2 = "192.168.0.1;192.168.1.9";
             String[] loc_ipIndex = loc_ip2.split(";");
             if(ip_ipAddr == null 
                     || "".equals(ip_ipAddr) 
                     || (ip_ipAddr.split("[.]").length < 4))
             {
                 return false;
             }
             
             String loc_minIp[] = loc_ipIndex[0].split("[.]");
             String loc_maxIp[] = loc_ipIndex[1].split("[.]");
             String loc_ip[] = ip_ipAddr.split("[.]");
             
             for(int i = 0;i < 4;i++)
             {
                 if((Integer.parseInt(loc_ip[i]) > Integer.parseInt(loc_maxIp[i])) 
                         || (Integer.parseInt(loc_ip[i]) < Integer.parseInt(loc_minIp[i])))
                 {
                     return false;
                 }
             }
             
             return true;
         }
         catch(Exception ip_exp)
         {
             ip_exp.printStackTrace();
             return false;
         }
    }
}