比较两个指针所指向的

comparing what two pointers point to

本文关键字:指针 两个 比较      更新时间:2023-10-16

我正在写一个检测网络钓鱼的程序。我试图检查如果URL的基础,如果它是相同的标签或不是。例如在http://maps.google.com"> www.maps.yahoo.com我试图检查URL的最后2部分是否相同,即如果google.com = yahoo.com或不。

我使用下面的代码:

void checkBase(char *add1, char *add2){
    char *base1[100], *base2[100];
    int count1 = 0, count2 = 0;
    base1[count1] = strtok(add1, ".");
        while(base1[count1] != NULL){
         count1++;
         base1[count1] = strtok(NULL, ".");
    }
    base2[count2] = strtok(add2, ".");
    while(base2[count2] != NULL){
    count2++;
    base2[count2] = strtok(NULL, ".");
    }
    if((base1[count1-1] != base2[count2-1]) && (base1[count1-2] != base2[count2-2])){
         cout << "Bases do not match: " << endl
          << base1[count1-2] << "." << base1[count1-1] << " and "
          << base2[count2-2] << "." << base2[count2-1] << endl;
    }
    else{
        cout << "Bases match: " << endl
              << base1[count1-2] << "." << base1[count1-1] << " and "
                  << base2[count2-2] << "." << base2[count2-1] << endl;
    }
 }

我不确定我在if语句中的比较是否正确。我传入了两个URL。由于

这是比较两个指针char*(正如你指出的;))

base1[count1-1] != base2[count2-1])

用这个代替

strcmp(base1[count1-1], base2[count2-1]) != 0

你可以使用std:stringboost标记器(现在c++ 11)

不能通过比较地址来比较字符串,两个相同的字符串可以存储在不同的地址中。要比较它们,你应该输入:

 if(strcmp(base1[count1-1], base2[count2-1]) != 0 || 
    strcmp(base1[count1-2], base2[count2-2])!=0){
        std::cout << "Bases do not match: " << std::endl
            << base1[count1-2] << "." << base1[count1-1] << " and "
            << base2[count2-2] << "." << base2[count2-1] << std::endl;
    }

你可以用c++工具做类似的事情:

void checkBase(std::string a1, std::string a2){
    size_t a1_start = a1.rfind('.'), a2_start = a2.rfind('.');
    a1_start = a1.rfind('.', a1_start-1);
    a2_start = a2.rfind('.', a2_start-1);
    std::string h1 = a1.substr(a1_start+1), h2 = a2.substr(a2_start+1);
    if (h1 == h2)
        std::cout << "same" << std::endl;
    else
        std::cout << "not same" << std::endl;
}