C/C++学习笔记

C++判断ip地址是否合法

2020-06-09  本文已影响0人  零岁的我

题目难度不大,主要想复习几个知识点。

  1. string类成员函数,特别是字符串查找函数find(),find()函数的第一个形参是要被搜索的字符串,第二个形参是在源串中开始搜索的下标位置,总是记反 :(
  2. 数字字符转数字。可以使用stoi()函数,还有一种方法就是使用c++标准库sstream,<sstream>库定义了三种类:istringstream、ostringstream、stringstream,分别进行流的输入、输出以及输入输出操作。可以实现对内存中的数据进行字符/数字转换。
    详情参考链接:https://www.jianshu.com/p/cafe63f670b9
  3. 使用正则表达式,对于字符序列的处理,推荐使用正则表达式,真的很间接,而且正则表达式的语法规则通用,c++、python等高级编程语言都有提供正则表达式包。
    参考链接:
    1)https://www.jianshu.com/p/e8158ea41906
    2)https://www.jb51.net/article/104447.htm
    3)https://www.jb51.net/article/174385.htm
/*题目描述
现在IPV4下用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此不需要用正号出现),如10.137.17.1,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。
现在需要你用程序来判断IP是否合法。
输入描述:
输入一个ip地址
输出描述:
返回判断的结果YES or NO
*/
#include<iostream>
#include<string>
#include<sstream>
#include<regex>

using namespace std;

bool isIp(string ipstr)
{
    int num;
    int j=0;
    for(int i=0;i<3;++i){
        int index=ipstr.find('.',j);
        num = stoi(ipstr.substr(j,index-j));
        if(num<0 || num>255) return false;
        j=index+1;
    }
    string end=ipstr.substr(j);
    for(int i=0;i<end.length();++i){
        if(end[i]<'0' || end[i]>'9') return false;
    }
    num = stoi(end);
    if(num<0 || num>255) return false;
    return true;
}

bool isIp1(string ipstr)
{
    istringstream ipstream(ipstr);
    int num[4];
    char point[3];
    string end;
    ipstream>>num[0]>>point[0]>>num[1]>>point[1]>>num[2]>>point[2]>>num[3]>>end;
    for(int i=0;i<3;++i){
        if(num[i]<0 || num[i]>255) return false;
        if(point[i]!='.') return false;
    }
    if(num[3]<0 || num[3]>255) return false;
    if(!end.empty()) return false;
    return true;
}

//使用正则表达式
bool isIp2(string ipstr)
{
    regex pattern("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
    smatch res;
    if(regex_match(ipstr,res,pattern)){
        return true;
    }
    return false;
}

int main(int argc,char **argv)
{
    string ipstr;
    while(cin>>ipstr){
        bool res=isIp2(ipstr);
        if(res){
            cout<<"YES"<<endl;
        }
        else{
            cout<<"NO"<<endl;
        }
        // isIp2(ipstr);
    }
    return 0;
}

上一篇下一篇

猜你喜欢

热点阅读