我正在测试一个小程序以创建一个更大的程序。 我有一个包含 3 个字符串的 vector :
pass
pass
TEST pass pass
我想在 vector 中搜索子字符串“pass”,并记录在字符串 vector 中找到“pass”的次数。
所以基本上我希望它返回数字 4(子字符串“pass”的 4 个实例)
代码是这样的
字符串存储在 vector myV1 中
if (find(myV1.begin(), myV1.end(), "pass") != myV1.end() )
{
passes++;
}
当我这样做时,它会发现一次“通过”并忽略其他。
我也无法使用循环。它告诉我,它找到了与我循环遍历的次数一样多的子字符串“通过”的许多实例。
提前感谢您的任何建议
最佳答案
简而言之:here您可以使用在线编译器找到工作代码。
您只需要两个循环,一个用于遍历 vector 元素,另一个循环遍历每个元素,同时计算该特定元素中所需单词的出现次数。然后外部循环对其进行总结。
您可以将 string::find 用于内部循环,而外部循环是带有迭代器的常规循环。
您需要下面的代码片段才能在 C++98/03 和 C++11 中正常工作。
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<string> stringList;
stringList.push_back("pass");
stringList.push_back("pass");
stringList.push_back("Test pass pass");
string searchWord = "pass";
int searchWordSize = searchWord.size();
int count = 0;
for (vector<string>::iterator iter = stringList.begin(); iter != stringList.end(); ++iter) {
// Avoid the overlapping search word. If that is needed, replace
// pos+=searchWordSize with ++pos
for (size_t pos = 0; pos < (*iter).length(); pos+=searchWordSize) {
pos = (*iter).find(searchWord, pos);
if (pos != string::npos)
++count;
else
break;
}
}
cout << "Count: " << count << endl;
return 0;
}
我已经使用以下命令构建并运行了代码:
g++ main.cpp
./a.out
如预期的那样,输出将是 4
。
关于c++ - 在字符串的VECTOR中记录特定子串出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18671315/