查找字符串中多个出现的子字符串[C++]

The*_* do 3 string substring

是否有任何STL算法或标准方法来查找字符串中特定子串的出现次数?例如在字符串中:

'How do you do at ou'
Run Code Online (Sandbox Code Playgroud)

字符串"ou"出现两次.我尝试了一些带有和没有谓词的STL算法,但我发现STL的那些算法想要比较字符串的组件,在我的例子中是char但不能?比较子串.我想出这样的事情:

str - string

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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 问题:在字符串"oooo"中你会将模式"oo"计算两次或三次.(Personnaly我会算三次,因此fo ++ pos而不是pos + = str.size().) (2认同)