算法题:判断字符串是否为 ipv4 地址

#include <stdio.h>

typedef char bool;
#define true 1
#define false 0


/**

   1.判断字符串是否形如“192.168.1.1”

   2.字符串两端含有空格视为合法ip,形如“    192.168.1.1    ”

   3.字符串中间含有空格视为非法ip,形如“192.168. 1.2”

   4.字符串0开头视为不合法ip,形如192.168.01.1

   5.字符串0.0.0.0视为合法ip
 */

bool checkIpv4(const char *ip){
    printf("检验对象是:%s\n", ip);
    if(NULL == ip) {
        return false;
    }
    const char *q = ip;     //字串指针
    unsigned short int s = 0, count = 0, digitNumber = 0;  //s是字串转化为的整型,count是 . 的个数, digitNumber 是 . 之间的数量
    bool hasZero = false;
    // 开头有空格
    while(' ' == *q) {
        q++;
    }

    while('\0' != *q) {
        if('.' == *q) {
            // . 前面没有任何值,则非法
            if(digitNumber == 0) {
                return false;
            }
            s = 0;
            digitNumber = 0;
            count++;

            hasZero = false;

            q++;

            continue;
        }

        // 值非法
        if(*q < '0' || *q > '9') {
            // 结尾空格
            if(' ' == *q && 3 == count) {
                const char *qq = q;
                while(' ' == *qq) {
                    qq++;
                }
                return '\0' == *qq;
            } else{
                return false;
            }
        }

        int x = *q - '0';
        s = s*10 + x;

        // 0.0.0.0 合法, 00.0.0.0 不合法
        if(0 == s) {
            if(hasZero) {
                return false;
            } else{
                hasZero = true;
            }
        }

        if(s > 255) {
            return false;
        }
        digitNumber++;
        q++;
    }
    return (3 == count);
}

int main(void){
    {
        const int count = 10;
        char *ip[count] = {"0.0.0.0", "255.255.255.255", "0.10.0.0", " 1.1.1.1", "1.1.1.1 ", " 1.1.1.1 "};
        for(int i = 0; i < count; i++) {
            if(checkIpv4(ip[i]))
                printf("该地址是IPv4地址\n");
            else
                printf("该地址不是IPv4地址\n");
        }
    }
    printf("\n\n");
    {
        const int count = 10;
        char *ip[count] = {"1.1.1. 1", "1..2.3", "00.1.1.1", "a.1.1.1", };
        for(int i = 0; i < count; i++) {
            if(checkIpv4(ip[i]))
                printf("该地址是IPv4地址\n");
            else
                printf("该地址不是IPv4地址\n");
        }
    }
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值