mirackara
mirackara

Reputation: 87

How would I search an element in a vector string?

I'm trying to search a vector string for certain words.

For example,

vector<string> sentences = ["This is a test string","Welcome to C++!"];
string searchString = "This";

I tried

if (std::find(sentences.begin(), sentences.end(), searchString) != sentences.end()) {
    cout << "Found!";
}
else {
    cout << "Not Found!";
}

Now this does work but only if the searchString matches the element word for word.

For example if we set

string searchString = "This is a test string";

This will return found.

How do I search the elements individually?

Thanks!

Upvotes: 1

Views: 4228

Answers (3)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122228

There is std::find_if that lets you pass a predicate to be used instead of directly comparing elements for equality with a searchString:

auto matcher = [searchString](const std::string& element) {
    return element.find(searchString) != std::string::npos;
};

if (std::find_if(sentences.begin(), sentences.end(), matcher) != sentences.end()){
    cout << "Found!";
} else {
    cout<< "Not Found!";
}

Upvotes: 2

ProXicT
ProXicT

Reputation: 1933

You can iterate over all the strings in your vector and check each string one by one if it contains the string you want to find. If the string contains the search term, you can return the whole element:

#include <iostream>
#include <vector>
#include <string>

std::string findSubstr(const std::vector<std::string>& list, const std::string& search) {
    for (const std::string& str : list) {
        if (str.find(search) != std::string::npos) {
            return str;
        }
    }
    return "Not found";
}

int main(int argc, const char** argv) {
    if (argc < 2) {
        std::clog << "Usage: " << argv[0] << " <search term>\n";
        return 1;
    }
    std::vector<std::string> test{"This is a test string", "Welcome to C++!"};
    std::cout << findSubstr(test, argv[1]) << std::endl;
}

Upvotes: 0

Adrian Costin
Adrian Costin

Reputation: 438

for(std::string& s  : sentences)
{
  if(s.find(searchString) != std::string::npos)
  {
     //substring found
  }
  else
  {
     //substring not found
  }
}

this should work for looking for a word in each string in the vector

Upvotes: 2

Related Questions