判断输入的字符串是否为合法IP
合法IP即为*.*.*.*形式,不允许出现前置0,之间不能有空格,每一段的数字在0-255之间,字符串前后允许有空格
#include <iostream>
#include "OJ.h"
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
bool isIPAddressValid(const char* pszIPAddr)
{
if(pszIPAddr == NULL)
return false;
int start = 0;
int end = 0;
int i;
//找到合法IP的头部与尾部
while(pszIPAddr[start] == ' ')
start++;
i = 0;
while(pszIPAddr[i] != '\0')
i++;
i--;
while(i >= 0 && pszIPAddr[i] == ' ')
i--;
end = i;
if(start >= end)
return false;
//cout<<"start = "<<start<<" "<<end<<endl;
//判断头部与尾部之间是否有空格
i = start;
int point = 0;
while(i <= end)
{
if(pszIPAddr[i] == '.')
point++;
if(pszIPAddr[i] == '.' && i+1 <= end && pszIPAddr[i+1] == '.')
return false;
if(pszIPAddr[i] == ' ')
return false;
if(pszIPAddr[i] != '.' && (pszIPAddr[i] < '0' || pszIPAddr[i] > '9'))
return false;
i++;
}
if(point != 3)
return false;
//cout<<"22222222222"<<endl;
//01
i = start;
while(i <= end)
{
if(i == start)
{
if(pszIPAddr[i] == '0' && (i+1 >= end || pszIPAddr[i+1] != '.'))
return false;
}
else if(pszIPAddr[i] == '.')
{
if(i+1 > end)
return false;
else if(pszIPAddr[i+1] == '0' && i+2 <= end && pszIPAddr[i+2] != '.')// 去掉02
{
return false;
}
}
i++;
}
//cout<<"3333333333"<<endl;
//0-255
i = start;
int sum = 0;
while(i <= end)
{
if(pszIPAddr[i] == '.')
{
if(sum < 0 || sum > 255)
return false;
sum = 0;
}
else
{
sum = sum * 10 + (pszIPAddr[i]-'0');
}
i++;
//cout<<sum<<endl;
}
if(sum < 0 || sum > 255)
return false;
return true;
}