计算字符串中字符串的出现次数

MBZ*_*MBZ 5 c++ string counting

计算字符串中所有子字符串出现次数的最佳方法是什么?

示例:计算Foo内部的出现次数FooBarFooBarFoo

tao*_*ocp 8

一种方法是使用 std :: string find函数:

#include <string>
#include <iostream>
int main()
{
   int occurrences = 0;
   std::string::size_type pos = 0;
   std::string s = "FooBarFooBarFoo";
   std::string target = "Foo";
   while ((pos = s.find(target, pos )) != std::string::npos) {
          ++ occurrences;
          pos += target.length();
   }
   std::cout << occurrences << std::endl;

}
Run Code Online (Sandbox Code Playgroud)

  • 重叠出现失败。 (5认同)

sha*_*ait 7

#include <iostream>
#include <string>

// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const std::string& str, const std::string& sub)
{
    if (sub.length() == 0) return 0;
    int count = 0;
    for (size_t offset = str.find(sub); offset != std::string::npos;
     offset = str.find(sub, offset + sub.length()))
    {
        ++count;
    }
    return count;
}

int main()
{
    std::cout << countSubstring("FooBarFooBarFoo", "Foo")    << '\n';

    return 0;
}
Run Code Online (Sandbox Code Playgroud)