I'm trying to write a program that return the number of occurrence of a sequence of letters in a string. I'm really confused with what i made up !! help me fix it please. :)
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
string seq; // the string to search for the occurrences
string s_pat; // the pattern to search for
char empty[1]="";
int s_pat_size=0;// the length of the search pattern
int repeat=0; // the number of occurrences
cout<< " Enter the sequence : \n";
cin>> seq;
cout<< " Enter the search pattern : \n";
cin>> s_pat;
for(int i=0;;i++)
{
if(s_pat[i]==empty[0]) break;
s_pat_size++;
}
// counting works !! test code --> cout<<" size of pattern : \n"<<s_pat_size<<endl;
for(int i=0;;i++)
{
if(seq[i]==empty[0]) break;
elseif(seq[i]==s_pat[0])
{
for(int j=0;;j++)
{
if(seq[i+j]!=s_pat[j]) break;
elseif(j=s_pat_size-1)
{
repeat++;
break;
}
}
}
}
cout<<" The pattern \" "<<s_pat<<" \" occurres "<<repeat<<" times "<<"in "<<seq<<endl;
}
1.I need it to check the end of the s_pat(search pattern) to count the number of letters in it // line 19
2.I need it to break the for loop in line 23 // see line 25.
I don't know if this is the right approach or not, that's just what came to my mind at the moment.
EDIT:line 19-20: do you know that the class string has a length() function that returns the length of the object?
You can use the function find() of the class std::string to find a substring.
http://www.cplusplus.com/reference/string/string/find/
I have written this function a time ago (and I've just rewritten it again :), try to understand it, and if you find bugs just don't hesitate to tell me:
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
string seq; // the string to search for the occurrences
string s_pat; // the pattern to search for
//no need ot these:
//char empty[1]="";
//int s_pat_size=0;// the length of the search pattern
int repeat=0; // the number of occurrences
cout<< " Enter the sequence : \n";
cin >> seq;
cout<< " Enter the search pattern : \n";
cin >> s_pat;
/*No need of this either,even if using c-style strings,we have strlen() in string.h
for(int i=0;;i++)
{
if(s_pat[i]==empty[0]) break;
s_pat_size++;
}
*/
for(int i = 0; i < seq.size(); ++i)
{
//if(seq[i]==empty[0]) break;
if(seq[i] == s_pat[0])
{
int j=0;
while(seq[i+j]==s_pat[j] && j < s_pat.size() && i+j < seq.size() )
++j;
if(j == s_pat.size())
++repeat;
}
}
cout<<" The pattern \" "<<s_pat<<" \" occurres "<<repeat<<" times "<<"in "<<seq<<endl;
}
Hey guys,
Thank u for the solutions, it worked.
To be honest, i didn't know that "string" is a class, i thought it was a type like "int".
I'm kinda new to C++ and i haven't got to the Classes part of the book I'm studying !! :)
Anyway I really appreciate your help, i learned a lot. :)