输入一个字符串,判断是否是合法的IP地址。
具体的做法是用'.'将字符串进行分割,分割后如果满足:1.有4部分 2.每部分是0-255的整数 则为合法的字符串。
但是由于c++里没有python中的split(貌似boost里有),所以要自己写一个split函数。这里借鉴了别人的写法(一开始我想暴力判断,后来发现行不通,还是要用分割来做)。
代码如下
// 5.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <sstream>
using namespace std;
void split(string& s, string& delim, vector<string>* ret)
{
size_t last = 0;
size_t index = s.find_first_of(delim, last);
while (index != string::npos)
{
ret->push_back(s.substr(last, index - last));
last = index + 1;
index = s.find_first_of(delim, last); //寻找下一个分割位置
}
//最后一个点之后的部分
if (index - last>0)
{
ret->push_back(s.substr(last, index - last));
}
}
bool checkIP(string tempIP)
{
vector<string> str;
string delim = ".";
split(tempIP, delim, &str);//分割字符串
if (str.size() != 4)
{
return false;
}
else
{
for (vector<string>::iterator iter = str.begin(); iter != str.end(); ++iter)
{
int transInt = 0;
stringstream ss;
ss << (*iter);
ss >> transInt; //借助stringstream转换整数
if (transInt<0 || transInt>255) //判断是否是合法的数字
{
return false;
}
}
return true;
}
}
int main()
{
string s;
while (cin >> s)
{
if (checkIP(s))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
system("pause");
return 0;
}