/*
Program for searching and counting number of occurences of a specific word in Entered
"STRING" using function.
*/
#include<iostream>
using namespace std;
//Function declaration
int wordSearch(char*,char[]);
int main()
{
int length;
char word[20];
//for getting length
cout << "Enter Approximate Sentence length?\t";
cin >> length;
//For clearing buffer
cin.ignore();
char *sentence = new char[length]; //declares new character array of entered
length on heap
//For Inputting Sentence
cout << "Enter Sentence?\n";
cin.getline(sentence, length);
cout << "Enter word u want to search in this string?\n";
cin >> word;
//For displaying result
cout << "Entered word occurs " << wordSearch(sentence,word) << "-time(s) in this string.";
cout << endl;
return 0;
}
//Function definition
int wordSearch(char* sentence,char word[])
{
int count = 0, l;
l = strlen(word); //Stores length of "word"
char *ptr = 0, *temp; //declares two char pointers
bool flag = 0;
ptr=strstr(sentence, word); //compare two strings and stores the starting
address of "word" in ptr if it exists in "sentence"
if (ptr != 0) //if "word" exists in "sentence" then "ptr" will not be zero
{
count++;
while (ptr != 0) //ptr will bw zero when "word" is not found in (remaining) "sentence"
{
temp = ptr;
ptr = strstr((ptr + l), word);
if (ptr!=0 && temp != ptr) //if "word" occurs again then address in ptr will not be same
count++;
}
}
//returns number of occurences of sentence
return count;
}
OUTPUT
No comments:
Post a Comment