1. 判断IP地址是否合法
描述:下面封装了两个函数,判断字符串中的IP是否合法。
#include <string> using namespace std;
bool CSettingDlg::isok(string str,int num) { int len=str.length(); int d=0; if(str=="0") return true; if(len>1&&str[0]=='0') return false; //有前导0,不合法 for(int i=0;i<len;i++) { if(!isdigit(str[i])&&str[i]!=' ') return false; if(str[i]==' ') { if(num==2||num==3) return false; else { if(num==1&&i!=0&&str[i]==' ') return false; if(num==4&&i!=len-1&&str[i]==' ') return false; } } if(isdigit(str[i])){ d=d*10+str[i]-'0'; } } if(d<0||d>255) return false; return true; } bool CSettingDlg::isIPAddressValid(const char* pszIPAddr) { // 请在此处实现 if(pszIPAddr==NULL) return false; string str=string(pszIPAddr); int len=str.length(); int coma_num; //=numberofComa(str); //计数点号,如果点号的个数不等于3个则为非法 //在str最后加上一个小数点,为了统计方便 str.append("."); //下面开始分割字符串,用点号进行分割,得到每个字符串,如果字符串,不合法,则返回false,不合法情况包括,字符串中间有空格,字符串有前导0,字符串中数字不再0-255之间,还有字符串为空,,这些都是不合法 //string::iterator iter_pre=str.begin(),iter_post; int iter_pre=0; int iter_post=str.find('.',iter_pre); if(iter_post==str.npos) return false; coma_num=0; while(iter_post!=str.npos) { coma_num++; string substr=str.substr(iter_pre,iter_post-iter_pre); if(substr=="") return false; if(!isok(substr,coma_num)) //如果不合法,跳出,并返回false { return false; } iter_pre=iter_post+1; iter_post=str.find('.',iter_pre); } if(coma_num!=4) return false; return true; }
调用:
if (!isIPAddressValid(m_strIP.GetBuffer())) { AfxMessageBox("IP不合法!!!"); return; }
2. 纯数字合法性描述:判断字符串中的内容是否都是数字。
if(!(strPort.SpanIncluding(_T("0123456789")) == strPort)) { AfxMessageBox("端口不合法,不是纯数字!!!"); return; }