jbaldwin
jbaldwin

Reputation: 924

std::count over variable string counting variable string

I'm trying to write a function to parse xml returned to me from an api, the data returned is very variable, so I need to ensure this function will work in all cases.

Here is the start of the function where my error is occurring (I believe)

using namespace std;
vector<string> grabXMLVals(string xmlString, string toFind){
    vector<string> values;
    int amount = (int)count(xmlString.begin(), xmlString.end(), &toFind); 
    for (int i = 0; i < amount; i++)

I want to count the amount of times the toFind string occurs in xmlString to know how many times my loop needs to run.

but when I compile with the count statement as is I get :

Error   1   error C2446: '==' : no conversion from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>> ' to 'int'  C:\Program Files\Microsoft Visual Studio 12.0\VC\include\xutility   3078    

Not sure which param it is not happy with, pretty sure its not the third because If I give a hardcoded constant it still is not happy, but I've found lots of people using std::count with std::string::begin and end online while searching for my answer, what are they doing that I'm not?

Upvotes: 0

Views: 291

Answers (1)

Nik Bougalis
Nik Bougalis

Reputation: 10613

Well, toFind is an std::string and &toFind takes its address. So what you are doing is this:

std::string const* addr = &toFind;
std::find (xmlString.begin(), xmlString.end(), addr); 

So you are trying to find a pointer inside a std::string which doesn't work.

What you want is something like this:

std::size_t count_substr(std::string const& str, std::string const& toFind)
{
    std::size_t count = 0;
    std::size_t pos = 0;

    while(pos != std::string::npos)
    {
        pos = str.find (toFind, pos);

        if (pos != std::string::npos)
        {
            /* increment the count */            
            count++;

            /* skip the instance of the string we just found */
            pos++;
        }
    }

    return count;
}

This is not the most elegant thing, but it should get you what you need.

Upvotes: 1

Related Questions