How to check if string is in array of strings

int size = (*array).size();

It will not tell you the size of array, it tells you the length of first string in that array, you should pass the length of array to the function separately. The function should look like:

bool in_array(string value, string *array, int length)

 

But a better choice is using std::vector and std::find:

#include <vector>
#include <algorithm>


bool in_array(const std::string &value, const std::vector<std::string> &array)
{
    return std::find(array.begin(), array.end(), value) != array.end();
}

and then, you can use it like:

std::vector<std::string> tab {"sdasd", "sdsdasd"};

if (in_array(n, tab))
{
    ...
}

When passing an array as an argument to a function which takes only a pointer, you can't query the size of the array within the function (since it got converted to a "stupid" pointer to the first element, nothing more). You typically add a "count" parameter to your signature or an "end" iterator instead.

What you're trying to implement is basically std::find. It takes two iterators (begin and end of the sequence) and the element to be found. Simply use this function.

std::find(std::begin(tab), std::end(tab), n);

will return an iterator to the element if it was found, the end iterator otherwise. Checking for equality with the end iterator will tell you if the element was found in the array.

If you don't like the "iterator interface" of the std algorithms, you can achieve your PHP-like signature by wrapping around std::find by using a template function:

template<class Element, class Container>
bool in_array(const Element & element, const Container & container)
{
    return std::find(std::begin(container), std::end(container), element)
            != std::end(container);
}

Please note: This answer assumes C++11. If you use an older compiler, it might not work or it only works if you add -std=c++11 to the compiler flags.


masoud answer is correct but it overly complicated. all you need is this.

bool isInVect=false;
isInVect = std::find(vector.begin(), vector.end(), stringToFind) != vector.end();
        
if (isInVect == true)
{
   cout << "Found string in Vector ..." << endl;
}

Tags:

C++

Arrays

String