计算一个字符串中一个字符串出现的次数 [英] Counting the number of occurrences of a string within a string

查看:124
本文介绍了计算一个字符串中一个字符串出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the best way of counting all the occurrences of a substring inside a string?

示例:计算 Foo FooBarFooBarFoo

Example: counting the occurrences of Foo inside FooBarFooBarFoo

推荐答案

使用 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;

}

这篇关于计算一个字符串中一个字符串出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆