0

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.

4
  • Are you checking to see if one of the elements in the vector is the same as the string or if one of the elements in the vector in contained within the string? Commented Jul 8, 2016 at 12:17
  • The second thing you mentioned. I'm trying to find out if on of the elements in the vector is contained within the string. Commented Jul 8, 2016 at 12:18
  • 1
    Looking at the documentation of System.String, I see a method named Contains that takes a String, and two that take single Chars. Where is this method that takes a whole array? Commented Jul 8, 2016 at 12:35
  • I suspect that you're using a custom String extension method, as it doesn't appear to be in dotnet. Commented Jul 8, 2016 at 12:39

4 Answers 4

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is exactly what I was looking for and it's working fine :)
0

Use a for loop and the find method.

Comments

0

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?

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.