One Of very commonly asked problem in Job Interviews is To find number of occurrence of given word in given paragraph . This very easy question but people still make mistakes .
How to do it :-
- Find first occurrence of first character of word in paragraph
- If found >> from that point check next character of word match with next character of paragraph
- Check until last character of word match with consecutive next character of paragraph
- If all character match increment count by 1.
- Repeat all above statement but now search perform on paragraph started at index of end of last character until which our search is completed
C++ Program to find no of Occurrence :-
- /*
- To check Occurrence of Given word in Given Paragraph
- >>Case sensitive
- */
- #include<iostream>
- #include<string.h>
- using namespace std;
- main(){
- char para[500];
- char word[20];
- int i,j,flag,count=0;
- cout<<"Enter Paragraph String : ";
- gets(para);
- cout<<"Enter Word to search : ";
- gets(word);
- i=0;
- while(i<strlen(para)){
- if(word[0]==para[i]){
- // if first element of word found check for rest of element
- // of word at consecutive position if all match found increment count
- i++;
- j=1;
- flag=1; //flag == True
- while(j<strlen(word)){
- if(word[j]!=para[i]){
- flag=0; //Mismatch found So flag=False
- break;
- }
- i++;
- j++;
- }
- if(flag) //if flag==True
- count++;
- }
- else
- i++;
- }
- cout<<"No of Occurence :: "<<count;
- return 0;
- }
Note :- We can use this technique to find all URL in a given webpage
Python >> Find Number of Occurrences :-
- # Find Occurrence Of Given Word In Given Paragraph
- # case-Insensitive
- def find_occ(para,word):
- '''
- Find Occurrence of word in para and return no of occurrence
- ->case Insensitive Search
- (string,string)->int
- '''
- Occurrence=0
- para=para.lower() #all in lowercase
- word=word.lower()
- index=-1
- while True:
- index=para.find(word,index+1) #if next word is not found return -1
- if index!=-1:
- Occurrence +=1
- else:
- break
- return Occurrence
- if __name__=='__main__':
- para=raw_input('Enter Paragraph :')
- word=raw_input("Enter word to Search :")
- print 'Occurence of "',word,'" in given paragraph is ::',find_occ(para,word)
- raw_input('\n\nhttp://beginer2cs.blogspot.com/')
Hello very cool site!! Guy .. Beautiful .. Amazing ..
ReplyDeleteI'll bookmark your blog and take the feeds alsoI am satisfied to find numerous useful
info right here in the publish, we'd like develop more strategies in this regard, thanks for sharing.
. . . . .
Here is my blog - book of ra online, www.bookofraspieler.com,
This comment has been removed by a blog administrator.
ReplyDelete