coder


私信TA

用户名:tomato

访问量:8959

签 名:

tomato

等  级
排  名 3236
经  验 1908
参赛次数 3
文章发表 10
年  龄 0
在职情况 学生
学  校 xynu
专  业 软件工程

  自我简介:

解题思路:
1.先判断输入格式是否为x.x.x.x,若果不是直接判断非法

2.遍历输入的字符串,当遍历到 ' . '时,将前面已经遍历的字符串存入临时字符串,再判断此字符串是否合法,然后清空临时字符串,继续遍历。

注意事项:
为保证遍历正确,需要在输入的字符串后面加一个' . ';
参考代码:

#include <iostream>
#include <string>
#include <algorithm>
#include <string.h>
#include <stdlib.h>
using namespace std;
//判断传进来的字符串是否合法 
bool isLetem(string s)
{
	for(int i=0; i<s.length(); ++i)
	{
		if(s.at(i)<'0' || s.at(i)>'9')//判断是否为数字 
			return false;
	}
	if(s.at(0)=='0' && s.length()>1) //判断是否为以0开始的数字 
		return false;
	int tem = atoi(s.c_str());
	if(tem>255)
		return false;
	return true;
}
bool isLegalityIP(string ip)
{
	string sip;
	string tem; //定义临时字符串 
	sip = ip;
	int i = 0;
	sip += '.';//为保证遍历正确,需要在输入的字符串后面加一个' . ' 
	while(i<sip.length())
	{
		if(sip.at(i)=='.')
		{
			if(!isLetem(tem))//调用isLetem(); 
				return false;
			else
			{
				tem.clear();//清空临时字符串
				i++;
				continue;
			}
		}
		tem += sip.at(i++);//将遍历的字符存入临时字符串
	}
	return true;
}
int main()
{
	string str;
	while(cin>>str)
	{
		if(str.find("End")!=string::npos)//输入End of file结束 
			break;
		if(count(str.begin(),str.end(),'.')!=3 || str.find("..")!=string::npos)//判断格输入式是否正确 
			cout<<'N'<<endl;
	    else if(isLegalityIP(str))
			cout<<'Y'<<endl;
		else
			cout<<'N'<<endl;
	}
	return 0;
}


 

0.0分

20 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区

我以为我写的够麻烦的了,没想到。。。你的比我写的还麻烦 。。。
2020-10-03 20:50:06
哇操,厉害呀
2020-04-24 18:17:36
if(count(str.begin(),str.end(),'.')!=3 || str.find("..")!=string::npos)//判断格输入式是否正确 
            请问这一句是什么意思啊,谢谢你
2020-01-27 19:29:41
  • «
  • 1
  • »