GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

count the number of times a pattern appears(may overlap) in a string. help correct my code??

 

#include<iostream>
#include<string>

using namespace std;

string text, pattern;

int countPattern(){
				int count=0,a;
				for(int i=0;i<(sizeof text- sizeof pattern);i++){
					
					for (a=0;a<sizeof pattern;a++){
						if(text[a+i]==pattern[a])
							continue;
						else
							break;

							}
					if(a==sizeof pattern){
						count++;
						}
							}
				
				return count;}
main(){
	cout<<"enter the text\n";
	cin>>text;
	cout<<"enter pattern\n";
	cin>>pattern;
	int c=countPattern();
	cout<<c;



}

 

asked Aug 24, 2016 by vanshika bawa

1 Answer

sizeof() function doesn't give the length of the string, instead use length function to find  the length.That seems to be an the main error .Also the for loop will have to run for text.lenght()-pattern.length()+1 times.

following is the modified code and it works for simple input like aaa,a or aaabbb,ab and gives correct output.check further,gotta go :)

 

//http://qa.geeksforgeeks.org/9099/count-number-times-pattern-appears-overlap-string-correct
#include<iostream>
#include<string>

using namespace std;

string text, pattern;

int countPattern(){
				int count=0,a;
				for(int i=0;i<(text.length()- pattern.length()+1);i++)
                {
                    // cout<<"In for loop"<<endl;
					for (a=0;a<pattern.length();a++)
                    {
						if(text[a+i]==pattern[a])
							continue;
						else
							break;

					}
					if(a==pattern.length())
                    {
						count++;
					}

				}
				
				return count;
}
main(){
	cout<<"enter the text\n";
	cin>>text;
	cout<<"enter pattern\n";
	cin>>pattern;
	int c=countPattern();
	cout<<c<<endl;

}

 

answered Aug 24, 2016 by prakharp
edited Aug 24, 2016 by prakharp
...