首页 > 解决方案 > 一个函数来查找字符串 1 包含字符串 2 多少次 c++

问题描述

我想检查我的第一个字符串包含第二个字符串的次数。我在互联网上读到了它,我找到了一个函数名std::find,我尝试使用它,但失败了......

std::string Str1 = "Hello Hello";
std::string Str2 = "ll";
Now what?

我试着用

标准::计数

也是,但我发现它只是在一个字母上工作。

counter = std::count(Str1.begin(), Str2.end(), Str2); // dident work

帮助??

编辑:这就是我想要做的:

unsigned int Nucleus::get_num_of_codon_appearances(const std::string& codon) const
{
    unsigned int counter = 0;
    counter = std::count(this->_DNA_strand.begin(), this->_DNA_strand.end(), codon);
    return counter;
}

标签: c++stringcountcontains

解决方案


如果您使用的是 c++11 或更高版本,则可以使用 std::regex 轻松完成此操作。

就像是,

#include <regex>
#include <iterator>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    const string str = "one two hello three four hello five hello";

    regex re("hello");
    cout << "Number of hellos : " <<  
        distance(sregex_iterator(str.begin(),str.end(), re),sregex_iterator());

}

演示


推荐阅读