簡體   English   中英

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

[英]A function to find how many times string 1 contains string 2 c++

我想檢查我的第一個字符串包含第二個字符串的次數。 我在互聯網上讀到它,然后發現一個函數名稱std :: find,我嘗試使用它,但失敗了...

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

我嘗試使用

的std ::計數

以及,但我發現它的工作只是在一個字母上。

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 ++ 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());

}

演示

您可以使用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");

正如paxbun所說,這里使用了string :: find方法,這是字符串類的內置函數。

.find()方法string :: find的引用〜C ++參考

作為包括與您的上述代碼相對應的類的另一種方法:

#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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM