3

文字列内に特定の部分文字列の出現回数を見つけるためのSTLアルゴリズムまたは標準的な方法はありますか?たとえば、文字列の場合:

'How do you do at ou'

文字列「ou」が2回表示されます。述語がある場合とない場合でいくつかのSTLアルゴリズムを試しましたが、STLのアルゴリズムは、文字列のコンポーネントを比較したいのですが、私の場合はcharですができません。部分文字列を比較します。私はこのようなものを思いつきます:

str-文字列

obj-私たちが探している部分文字列

std::string::size_type count_subs(const std::string& str, const std::string& obj)
{
std::string::const_iterator beg = str.begin();
std::string::const_iterator end = str.end();
std::string::size_type count = 0;
while ((beg + (obj.size() - 1)) != end)
{
    std::string tmp(beg, beg + obj.size());
    if (tmp == obj)
    {
        ++count;
    }
    ++beg;
}
return count;
}

ありがとうございました。

4

1 に答える 1

5
#include <string>
#include <iostream>

int Count( const std::string & str, 
           const std::string & obj ) {
    int n = 0;
    std::string ::size_type pos = 0;
    while( (pos = obj.find( str, pos )) 
                 != std::string::npos ) {
        n++;
        pos += str.size();
    }
    return n;
}

int main() {
    std::string s = "How do you do at ou";
    int n = Count( "ou", s );
    std::cout << n << std::endl;
}
于 2009-12-03T10:44:11.200 に答える