You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.4 KiB
56 lines
1.4 KiB
/*
|
|
验证ipv4是否合法
|
|
|
|
*/
|
|
#include <bits/stdc++.h>
|
|
using namespace std;
|
|
|
|
vector<string> split(string s, string spliter) {
|
|
vector<string> res;
|
|
int i;
|
|
//遍历字符串查找spliter
|
|
while ((i = s.find(spliter)) && i != s.npos) {
|
|
//将分割的部分加入vector中
|
|
res.push_back(s.substr(0, i));
|
|
s = s.substr(i + 1);
|
|
}
|
|
res.push_back(s);
|
|
return res;
|
|
}
|
|
bool isIPv4(string IP) {
|
|
vector<string> s = split(IP, ".");
|
|
if (s.size() != 4)
|
|
return false;
|
|
for (int i = 0; i < s.size(); i++) {
|
|
//不可缺省,有一个分割为零,说明两个点相连
|
|
if (s[i].size() == 0)
|
|
return false;
|
|
//比较数字位数及不为零时不能有前缀零
|
|
if (s[i].size() < 0 || s[i].size() > 3 || (s[i][0] == '0' && s[i].size() != 1))
|
|
return false;
|
|
//遍历每个分割字符串,必须为数字
|
|
for (int j = 0; j < s[i].size(); j++)
|
|
if (!isdigit(s[i][j]))
|
|
return false;
|
|
//转化为数字比较,0-255之间
|
|
int num = stoi(s[i]);
|
|
if (num < 0 || num > 255)
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
int solve(string IP) {
|
|
// write code here
|
|
if (IP.size() == 0)
|
|
return 0;
|
|
if (isIPv4(IP))
|
|
return 1;
|
|
return 0;
|
|
}
|
|
int main() {
|
|
string str;
|
|
cin >> str;
|
|
cout << solve(str) << endl;
|
|
return 0;
|
|
}
|