C++ : Checking whether a string vector has a specific string
假设,我有一个字符串向量,比如说32000个元素的
我想使用一个
假设,我在
1 2 3 4 | table[0]="starved monster" table[1]="rabid mosquito" table[2]="drunk ghost" // ... |
我想迭代整个向量来检查它是否有子字符串,
因为在这里,它实现了,我想实现一个代码,它说:
Yes the substring is there and it is at index=2.
您可以使用
1 2 3 4 5 6 7 8 9 10 11 | std::string toFind = ...; auto iter = std::find_if( table.begin(), table.end(), [&](const std::string &str){ return str.find(toFind) != std::string::npos; } ); if (iter != table.end()) { auto index = std::distance(table.begin(), iter); ... } |
您可以简单地循环遍历向量,并使用std:string::find方法查找字符串。
下面是一个简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> #include <iomanip> #include <vector> using namespace std; int main() { const vector<string> table {"hello","hi","bye","see you" }; const string str_to_find {"you" }; for ( size_t i = 0; i < table.size(); ++i ) { if ( table[i].find( str_to_find ) != string::npos ) { cout <<"Found" << quoted( str_to_find ) <<" in" << quoted( table[i] ) <<" at index" << i << ' '; break; } } return 0; } |
输出:
Found"you" in"see you" at index 3
您可能需要为此编写一个简单的方法,该方法将适当地返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> table; table.push_back("starved monster"); table.push_back("rabid mosquito"); table.push_back("drunk ghost"); //entries for rest of the table string toFind ="ghost"; for (int ii = 0; ii < table.size(); ++ii){ if (table[ii].find(toFind) != string::npos) { cout <<"Yes the substring is here and it is at index" << ii << endl; } } return 0; } |