Я хочу проверить, сколько раз моя первая строка содержит вторую строку.
Я прочитал об этом в Интернете, и я нашел имя функции 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;
}
Вы можете сделать это довольно легко с помощью std :: regex, если вы используете c ++ 11 или выше.
Что-то вроде,
#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, который является встроенной функцией класса string.
Ссылка на метод .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