通俗易懂兄弟们 最短ip : 1.1.1.1 长度为7 最长ip: 255.255.255.255 长度为15
然后就是判断每个点之前的temp字符串是否为合法的1-255数字,很简单。 记得ip不能以0开头,022是非法的
int toInt(string a) {
int len = a.size();
int res = 0;
for (int i = 0; i < len; i++) {
res = res * 10 + int(a[i] - 48);
}
return res;
}
bool isIP(string & str) {
bool flag = true;
int len = str.size();
if (len < 7 or len > 15) {
return false;
}
if (str[0] == '.' || str[len - 1] == '.') return false;
string temp = "";
for (int i = 0; i < len; i++) {
if (str[i] != '.') {
temp += str[i];
continue;
}
else {
if (temp[0] == '0') return false;
for (int j = 0; j < temp.size(); j++) {
if (isdigit(str[j])) {
continue;
}
else {
return false;
}
}
int a = toInt(temp);
if (a >= 1 and a <= 255) {
temp = "";
continue;
}
else {
return false;
}
}
}
if (temp[0] == '0') return false;
for (int j = 0; j < temp.size(); j++) {
if (isdigit(str[j])) {
continue;
}
else {
return false;
}
}
int a = toInt(temp);
if (a >= 1 and a <= 255) {
temp = "";
}
else {
return false;
}
return true;
}
int main()
{
string ip;
while (cin >> ip) {
if (isIP(ip)) {
cout << "That's true IP ! " << endl;
}
else if (ip == "stop") {
return 0;
}
else {
cout << "Sorry , it's wrong IP" << endl;
}
}
}
测试用例
?根据长度,字符是否合法进行设计用例吧
|