IP地址判断

输入一个字符串,判断是否是合法的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;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值