Terence Da Silva
Terence Da Silva

Reputation: 21

Partial string search in C++

Let's say I have a vector of strings called info that reads names of websites from a file one by one sequentially.

This is what I have that searches for names, by the complete name only:

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;
}

Now what if I wanted to COUNT the amount of websites with a particular word in it?

So if I had

  1. apple.com
  2. mac.com
  3. macapple.com
  4. applepie.com
  5. potato.com

and I searched for "apple", it would return 3.

Upvotes: 0

Views: 7392

Answers (1)

sam
sam

Reputation: 2033

You can use string::find to perform a partial search of the string and store the value into a size_t variable.

Compare that to std::string::npos and increment count if they are not equal.

Here is an simple example using arrays not vector so you can learn and make modifications as required.

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;
}

Here is the link for the code above. You can see that the output is 2 as expected as the word stack occurs twice in the inputs array.

Upvotes: 1

Related Questions