C++ 字符串中子串个数

子串可重叠情况:


int fun1(const std::string& str, const std::string& sub){   int num = 0;   for (size_t i = 0;
     (i = str.find(sub, i)) != std::string::npos;
     num++, i++);   return num; }

 

子串不可重叠情况:


int fun2(const std::string& str, const std::string& sub){   int num = 0;   size_t len = sub.length();   if (len == 0)len=1;//应付空子串调用   for (size_t i=0;
    (i=str.find(sub,i)) != std::string::npos;
    num++, i+=len);   return num; }


posted @ 2020-06-20 17:28  HDAWN  阅读(1442)  评论(0编辑  收藏  举报