需求 判断 IP 是否在 1网段,思路是判断字符串里是否包含192.168.1 ,找了3个方法:
char *strstr(const char *str1, const char *str2);
此函数的功能为查询字符串 str2 是否是 str1 的子串,如果是,返回字符串str2在str1中出现的头一个位置的指针*char。如果不是,则返回null;
substr(size_type __pos = 0, size_type __n = npos) const
获得字符串s中 从第0位开始的长度为n 的字符串 ,第一个参数是起始位置,第二个参数是切割长度
char * __cdecl strcpy(char * __restrict__ _Dest,const char * __restrict__ _Source);
将一个字符串的内容复制到另一个字符串中
int __cdecl strcmp(const char *_Str1,const char *_Str2);
把 str1 所指向的字符串和 str2 所指向的字符串进行比较(1、若参数1>参数2,返回正数;2、若参数1<参数2,返回负数;3、若参数1=参数2,返回0;)
std::vector<std::string> ipls= whudp.getIpList(); // ip地址集合
for(int i=0;i<ipls.size();i++){
// 1
const char * ip= ipls[i].c_str();
// char str2[] = "192.168.1.";
// char * ss = strstr(ip, str2);
char * ss = strstr(ip, "192.168.1.");
if(ss == nullptr) {// 地址
cout << "no-==== " << ip << endl;
continue;
}
// 2
string ss = ipls[i].substr(0, 10);
if(ss == "192.168.1.") {
cout << "yes-==== " << ss << endl;
}
// 3
char t[100] = {0};
char str2[] = "192.168.1.";
const char * ip= ipls[i].c_str();
strcpy(t, ip);
if (strcmp(t, str2) == 0){
cout << "yes-==== " << ip << endl;
} else {
cout << "no==== " << ip << endl;
}
}