这对我来说真的很难,我该怎么办

this is really hard for me, and what should i do?

本文关键字:很难 我该怎么办 说真的      更新时间:2023-10-16

我的问题在C 中。如何比较两个不同的长度字符串。例如string a = "ap" string b = "apple"。因此,最后一场比赛应该是1,或考虑另一个示例,例如string a = "123" string b = "123123123",最后一场比赛应为3。因此,我认为我尝试让a[i]= b[i],但仅比较1个charcater。如何比较muliple长度字符串。

int getMatchCount(string a, string b)
{
    int match = 0;
    if (a.length() == 0 or b.length() == 0 )
    {
        return -1;
    }
    for (int i = 0; i < a.length(); i++)
    {
        if( string.compare(a, b) )
        {
            match = match +1;
        }
    }
    return match;
}

这是一个天真的,但可行的解决方案:

#include <iostream>
#include <string>
#include <algorithm>
int main(int argc, const char * argv[]) {
    std::string first = "hello";
    std::string second = "hello_world";
    int match = 0;
    for (int i = 0; i < std::min(first.length(), second.length()); ++i) {
        if(first.at(i) == second.at(i)) {
            match++;
        } else {
            break;
        }
    }
    std::cout << match << std::endl;
    return 0;
}

因为请求:

#include <algorithm>在那里用于std::min()功能,以避免访问无效的内存地址。也就是说,它可以防止for循环访问大于string.length()的任何string索引,这将导致不确定的行为...或者在我学习C 时返回segmentation fault

在这种情况下,它已被某些逻辑和短手三元运算符替换。

#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
    string first = "hello";
    string second = "hello_world";
    int match = 0;
    size_t lowest = first.length() <= second.length() ? first.length() : second.length();
    for (int i = 0; i < lowest; ++i) {
        if(first.at(i) == second.at(i)) {
            match++;
        } else {
            break;
        }
    }
    cout << match << endl;
    return 0;
}

使用std::string::find

解决方案
#include <iostream>
int getMatchCount(std::string a, std::string b)
{
    int match = 0;
    std::size_t pos = 0;
    while ((pos = b.find(a, pos)) != std::string::npos) {
        ++pos;
        ++match;
    }
    return match;
}
int main() {
    std::cout << getMatchCount("is", "isis");
    return 0;
}

编辑我使用std::size_t,因为我想将其与std::string::npos进行比较。int不能保证足够大,无法做到这一点。std::size_t也是未签名的,这使其成为表示索引的好选择。

如果我们分解循环,它将运行b.find(a, pos),这将在字符串b中找到子字符串a的第一次发生。如果找到匹配项,则返回值是子字符串启动的索引,或者如果找不到 std::string::npos

第一次运行 pos0,因此我们从搜索时从字符串B的开头开始。然后,我们将返回的值存储在pos中。(在我们的示例中,第一次比赛将再次是0(

如果返回值不是std::string::npos,我们找到了匹配项,因此我们增加了match。对于循环的下一次迭代,我们希望在上一场比赛之后启动搜索,因此我们将pos递增。(在我们的示例中,我们将其增加到1,然后搜索从索引1及以前开始的子字符串(