C++中的部分字符串搜索

Partial string search in C++

本文关键字:字符串 搜索 C++      更新时间:2023-10-16

假设我有一个名为info的字符串向量,它按顺序从文件中逐个读取网站名称。

这就是我所拥有的搜索名称的功能,仅通过完整的名称:

int linearSearch(vector <string> inputs, string search_key){
    for (int x=0; x<inputs.size(); x++){
        if (search_key==inputs[x]){
            return x;
        }
    }
    return -1;
}

现在,如果我想计算其中包含特定单词的网站数量,该怎么办?

所以如果我有

  1. apple.com
  2. mac.com
  3. macapple.com
  4. 苹果网
  5. potato.com

如果我搜索"apple",它会返回3。

您可以使用string::find对字符串执行部分搜索,并将值存储到size_t变量中。

将其与std::string::npos进行比较,如果它们不相等,则递增计数。

这里有一个简单的例子,使用数组而不是向量,这样您就可以根据需要进行学习和修改。

int main() {
    string inputs[2] = {"stack overflow", "stack exchange"};
    string search_key = "stack";
    int count;
    for(int i = 0; i <sizeof(inputs)/sizeof(inputs[0]); i++)
    {
        //npos returns -1. If substring is not found, find will return -1.
        //if substring is found, condition fails and count is incremented 
        if (inputs[i].find(search_key) != string::npos)
            count++;
    }
    cout << count;
    return 0;
}

这是上面代码的链接。您可以看到,由于字stackinputs数组中出现两次,因此输出为2。