在基于Internet的程序中,我们常常需要判断一个IP字符串的合法性。
合法的IP是这样的形式:
A.B.C.D
其中A、B、C、D均为位于[0, 255]中的整数。为了简单起见,我们规定这四个整数中不允许有前导零存在,如001这种情况。
现在,请你来完成这个判断程序吧^_^
解法:
.遍历输入的字符串,当遍历到 ' . '时,将前面已经遍历的字符串存入临时字符串,再判断此字符串是否合法,然后清空临时字符串,继续遍历。
#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;
}
string::npos参数 —— npos 是一个常数,用来表示不存在的位置
有两个字符串a、b,判断a字符串是否包含b字符串
//如果字符串不存在包含关系,那么返回值就一定是npos
if(a.find(b)!=string::npos){
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;
atoi()函数会会扫描参数字符串,跳过前面的空白字符(例如空格,tab缩进等),
直到遇到数字或者正负符号才开始做转换,遇到非数字或字符串结束时(‘\0’)才结束转换,
并将结果返回。如果参数不能转换成int或者参数为空字符串,则将返回0.
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str1 = "237";
int a = atoi(str1.c_str());
cout<<a<<endl;
return 0;
}