函数原型: bool IsValidIP(const char* szIP)
举例说明:
“not is ip string”的判断结果为false;
“1.2.34”的判断结果为false;
“111.222.333.444”的判断结果为false;
“1.2.3.4”的判断结果是true。
要求:尽量不使用库函数,尽可能提高函数健壮性。
#include<iostream>
#include<string.h>
using namespace std;
bool IsVaildIp(const char* szip)
{
unsigned int len = strlen(szip);
if(len > 15)
{
cout<<"this is unvalidity ip0"<<endl;
return false;
}
int ar[4] = {0};//用来存分割开IP地址的字符个数
const char* str = szip;
unsigned int i = 0;//统计.的个数
char* ptr = (char*)malloc(sizeof(char)*4);//存分割开的IP字符串
while(*str != '\0')
{
if(*str!='.' && (*str>'9'||*str<'0'))//不是ip地址中合法字符
{
cout<<"this is unvalidity ip1"<<endl;
return false;
}
else if(*str != '.')
{
if(++ar[i] > 3)//分割的字符串个数大于3则不合法
{
cout<<"this is unvalidity ip2"<<endl;
return false;
}
strncat(ptr,str,1);
}
else if(*str == '.')
{
++i;
memset(ptr,0,4);//每遇到一个.重置ptr
}
if(atoi(ptr)>atoi("255") || atoi(ptr)<atoi("0"))
//分割的字符串不在0到255之间不合法
{
cout<<"this is unvalidity ip3"<<endl;
return false;
}
++str;
}
if(i != 3)//ip4地址必须为四段
{
cout<<"this is unvalidity ip4"<<endl;
return false;
}
cout<<"this is validity ip0"<<endl;
free(ptr);
return true;
}
void main()
{
char* szip = "not is ip str";
cout<<IsVaildIp(szip)<<endl;
}
以上是使用库函数的实现方法。题目要求尽量不使用库函数,要多次使用if else语句,代码冗余量太大。
#include<iostream>
#include<string.h>
using namespace std;
bool IsVaildIp(const char* szip)
{
unsigned int len = strlen(szip);
if(len > 15)
{
cout<<"this is unvalidity ip0"<<endl;
return false;
}
int ar[4] = {0};
const char* str = szip;
unsigned int i = 0;
unsigned int j = 0;
const char *ptr1=NULL,*ptr2=NULL,*ptr3=NULL;
while(*str != '\0')
{
if(*str!='.' && (*str>'9'||*str<'0'))
{
cout<<"this is unvalidity ip1"<<endl;
return false;
}
else if(*str!='.')
{
++ar[i];
if(ar[i] == 1)
{
ptr1 = str;
}
else if(ar[i] == 2)
{
ptr2 = str;
}
else if(ar[i] == 3)
{
ptr3 = str;
}
else
{
cout<<"this is unvalidity ip2"<<endl;
return false;
}
}
else if(*str == '.')
{
++i;
}
if(ar[i] == 3)
{
if(*ptr1>'2'||*ptr1<'0')
{
cout<<"this is unvalidity ip3"<<endl;
return false;
}
else if((*ptr1=='2' && (*ptr2>'5'||*ptr2<'0')))
{
cout<<"this is unvalidity ip4"<<endl;
return false;
}
else if(*ptr1=='2' && *ptr2=='5' && (*ptr3>'5'||*ptr3<'0'))
{
cout<<"this is unvalidity ip5"<<endl;
return false;
}
}
++str;
}
if(i != 3)
{
cout<<"this is unvalidity ip6"<<endl;
return false;
}
cout<<"this is validity ip0"<<endl;
return true;
}
void main()
{
char* szip = "99.255.107.130";
cout<<IsVaildIp(szip)<<endl;
}