-4

Suppose, I have a string vector, table of say 32000 elements.

I want to use an if loop to check whether the vector has (even a substring of the) string.

Suppose, my first three elements of table are,

table[0]="starved monster"
table[1]="rabid mosquito"
table[2]="drunk ghost"
// ...

I want to iterate over this entire vector to check whether it has a substring, s="gho";

Since here, it does, I want to implement a code that says:

Yes the substring is there and it is at index=2.

Dean Seo
  • 5,486
  • 3
  • 30
  • 49
onie
  • 13
  • 4

3 Answers3

1

You can simply loop through the vector and use std:string::find method to find the string.

Here's a simple example:

#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 << '\n';
            break;
        }
    }

    return 0;
}

Output:

Found "you" in "see you" at index 3

You may want to write a simple method for this that would return true/false appropriately along with the index (valid index on success, -1 otherwise).

Azeem
  • 11,148
  • 4
  • 27
  • 40
1

You can use std::find_if(), eg:

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);
    ... 
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0
#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;
}
gorlux
  • 129
  • 5