查找字符串1包含字符串2的次数的函数C ++

时间:2018-10-28 23:30:13

标签: c++ string count contains

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

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

我尝试使用

  

std :: count

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

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

3 个答案:

答案 0 :(得分:2)

如果您使用的是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());

}

Demo

答案 1 :(得分:1)

您可以使用std :: string :: find。

#include <string>
using namespace std;

size_t count (const string & src, const string & str) {
    size_t cnt = 0, fnd = 0;
    while (fnd = (src.find(str, fnd)) != string::npos) {
        cnt++; fnd++;
    }
    return cnt;
}

...

count("Hello, world!", "ll");

答案 2 :(得分:0)

paxbun所述,此处使用了string :: find方法,它是字符串类的内置函数。

.find()方法的引用string::find ~ C++ Reference

作为另一种方法,包括与您上面的代码相对应的类:

#include <iostream>
#include <string>

using namespace std;

//class declaration
class Nucleus{
private:
 string _DNA_strand{"ABCADDASDASABCAFGDACCACABCDA"};

public:
    const string get_codon(){return _DNA_strand;} //accessor of private variable
    unsigned int get_num_of_codon_appearances(const string& _DNA_strand, const string& ) const;
};

//Function  to return the number of times a string is found within another string.
unsigned int Nucleus::get_num_of_codon_appearances(const string& codon, const string& c) const
{
    unsigned int count = 0; //sets count
    size_t counter = 0; //sets counter
    while (counter != string::npos) // if counter does not equal string no position
    {
            size_t i = counter + c.length(); // sets i to counter + length of searched for object
            counter = codon.find(c, i); // .find() method 
            count++;
    }
    return count;
}

//Main Function
int main()
{
    Nucleus temp; //sets the object temp of the class Nucleus
    const string codon = temp.get_codon();
    const string c = "ABC";

    cout << "The Number of times " << c << " is found in " 
    << temp.get_codon() << " is: " << temp.get_num_of_codon_appearances(codon, c) << endl;

    return 0;   
}

示例输出:

The Number of times ABC is found in ABCADDASDASABCAFGDACCACABCDA is: 3

DEMO