首页 > 试题广场 >

给你一个字符串,你怎么判断是不是ip地址?手写这段代码,并写

[问答题]

给你一个字符串,你怎么判断是不是ip地址?手写这段代码,并写出测试用例

LeetCode468
发表于 2021-07-04 15:35:07 回复(0)
s = input('input ip :').split('.')
#输入是一个列表,其中的数字是字符;
counter = 0
#负号不是数字,会判定为非正数。isdigit()
for i in range(len(s)):
    # 测试要点1:是正数且第一个数不等于0,后面的数都小于等于255;
    if s[i].isdigit() == True and int(s[0]) > 0 and int(s[i]) <= 255:
        counter +=1
    else:
        pass
# 测试要点2:长度等于4且满足条件1;
if counter == 4 and len(s) == 4:
    print("input string is IP address")
else:
    print("input string is not a Ip Address")


编辑于 2021-08-18 15:25:03 回复(0)
s = input("请输入一个字符串,并判断是否为ip地址 > ").split(".")
counter = 0
counter= [int(x)<=255 if x.isdigit() else False for x in s].count(True)

if counter == 4 and len(s) == 4:
    print("input string is IP address")
else:
    print("input string is not a Ip Address")
发表于 2021-07-06 15:11:15 回复(1)
        Scanner sc = new Scanner(System.in);
        System.out.println("输入字符串");
        String ip = sc.nextLine();
        String[] s = ip.split("\\.");     //把输入的字符串按照 . 分割
        for (int i = 0; i < s.length; i++) {
            if(!((Integer.valueOf(s[i])>0)&&(Integer.valueOf(s[i])<255))){    //判断每段范围是不是在0~255
                System.out.println("这不是ip地址");
            }
        }
发表于 2021-07-05 11:20:40 回复(0)