且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-13 16:58:29

使用 std :: string查找函数:

#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;

}