wordiboi
wordiboi

Reputation: 59

Efficient way to check if string contains value of vector<string>?

I'm pretty new to C++ programming but for certain reasons I need to develop a small tool in C++. I've written the same tool in C# already. Right now I'm trying to check if my string contains a value that is stored in a std::vector. In C# this is pretty straight forward, simply using something like this:

if(string.Contains(myarray)) { // do sth. }

In C++ this seems way harder to achieve. I googled quite a bit but so far I found only solutions to check if the WHOLE string exists in an array and not just a certain part of it.

Upvotes: 0

Views: 814

Answers (4)

user2807083
user2807083

Reputation: 2982

If you need more effective way to find several substrings in string than straightforward find string-by-string, you can use Aho-Corasick algorithm It uses trie to hold substrings. First google link to c++ implementation

Upvotes: 0

Daniel
Daniel

Reputation: 1447

I would suggest std::find_first_of

Not sure if I understood your exact problem, though. Could you give a small example of what your are trying to find in what?

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180990

Unfortunately std::string does not have a method that can see if a element of a vector is in a string like C# does. What it does have though is std::string::find which can determine if a string is contained within the string you call find on. You could use that like

std::vector<std::string> words;
// fill words
std::string search_me = "some text";
for (const auto & e : words)
{
    if (search_me.find(e) != std::string::npos)
    {
        // e is contained in search me.  do something here
        // call break here if you only want to check for one existence
    }
}

This is O(N*complexity_of_find).

Upvotes: 3

Mike Graham
Mike Graham

Reputation: 76773

Use a for loop and the find method.

Upvotes: 0

Related Questions