文字列内に特定の部分文字列の出現回数を見つけるための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;
}
ありがとうございました。