i am tryng to count the ocurrence of a std::string inside another std::string using this:

   static int cantidadSimbolos(const std::string & aLinea/*=aDefaultConstString*/,
                                  const std::string & aSimbolo/*=aDefaultSimbolSeparador*/)
        {
            if(aSimbolo.empty()) return 0;
            if (aLinea.empty()) return  0;
            int aResultado=0;
//This is the line that the compiler doesnt like
           aResultado=std::count(aLinea.begin(),aLinea.end(),aSimbolo);
            return aResultado;
        }

but the compiler doesnt like it, this is the error that the compiler emits:

error: no match for ‘operator==’ in ‘_first._gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* >() == __value’

any help?? thx in advance!

有帮助吗?

解决方案

The following code will find the count of the non-overlapping occurrences of a given string.

using namespace std;

static int countOccurences(const string & line, const string & symbol) {

if (symbol.empty()) return 0;
if (line.empty()) return 0;
int resultCount = 0;

for (size_t offset = line.find(symbol); offset != string::npos;
     offset = line.find(symbol, offset + symbol.length()))
{
    resultCount++;
}

 return resultCount;

}

int main(int argc, const char * argv[])
{
    cout << countOccurences("aaabbb","b") << endl;

    return 0;
}

The find function will return either an iterator to the first element of the value it matches to or return 'last' hence string::npos. This ensures no overlap with offset + symbol.length().

I did my best to translate the variables to English for readability for English users.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top