C++中的部分字符串搜索
Partial string search in C++
假设我有一个名为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;
}
现在,如果我想计算其中包含特定单词的网站数量,该怎么办?
所以如果我有
- apple.com
- mac.com
- macapple.com
- 苹果网
- 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;
}
这是上面代码的链接。您可以看到,由于字stack
在inputs
数组中出现两次,因此输出为2。
相关文章:
- 哪个更快:在 1d 向量中按字符串搜索还是在 2d 向量中按向量搜索?
- 有序地图字符串搜索与整数搜索之间的时间复杂度
- 使用图形的字符串搜索算法?C++
- C++子字符串搜索 - 跳入C++
- 字符串搜索 - 并行版本较慢
- 使用Robert Sedwick书中的符号表进行字符串搜索
- C++中的部分字符串搜索
- 哪个是更好的字符串搜索算法?Boyer-Moore或Boyer Moore Horspool
- 如何使用 c++ 将字符串搜索到字符串数组中
- 使用 C++ 在文件中进行字符串搜索/索引
- Qt5 中字符串搜索的最佳容器
- 优化.txt文件中的字符串搜索
- 字符串搜索输入中包含的单词
- Boyer-Moore-坏字符规则实现子字符串搜索
- 带星号*通配符的字符串搜索
- c++字符串搜索函数
- 最好的字符串搜索算法
- 通配符字符串搜索算法
- 在c++中使用字符串(搜索字符串,分割字符串,cout<<字符串)
- Strstr()函数重叠字符串搜索